<< back to Guides

πŸ“˜ Deep Dive into Sorting Algorithms


πŸ“¦ What is Sorting?

Sorting is the process of arranging data in a particular format or order β€” typically ascending or descending. It’s one of the most fundamental operations in computing, enabling faster searches, easier visualization, and efficient data structures.


🧠 Why Sorting Matters


🧰 Classification of Sorting Algorithms

Criteria Type Examples
Time Complexity Comparison-based vs Non-Comparison Merge Sort, Counting Sort
Stability Stable vs Unstable Merge Sort (stable), Quick Sort (unstable)
In-place In-place vs Not Quick Sort (in-place), Merge Sort (not)
Adaptiveness Adaptive vs Non-Adaptive Insertion Sort (adaptive), Merge Sort (not)

πŸ”„ Common Sorting Algorithms

1. Bubble Sort

func bubbleSort(arr []int) {
	n := len(arr)
	for i := 0; i < n-1; i++ {
		for j := 0; j < n-i-1; j++ {
			if arr[j] > arr[j+1] {
				arr[j], arr[j+1] = arr[j+1], arr[j]
			}
		}
	}
}

2. Selection Sort


3. Insertion Sort


4. Merge Sort

func mergeSort(arr []int) []int {
	if len(arr) <= 1 {
		return arr
	}
	mid := len(arr) / 2
	left := mergeSort(arr[:mid])
	right := mergeSort(arr[mid:])
	return merge(left, right)
}

func merge(left, right []int) []int {
	result := []int{}
	i, j := 0, 0
	for i < len(left) && j < len(right) {
		if left[i] <= right[j] {
			result = append(result, left[i])
			i++
		} else {
			result = append(result, right[j])
			j++
		}
	}
	result = append(result, left[i:]...)
	result = append(result, right[j:]...)
	return result
}

5. Quick Sort


6. Heap Sort


7. Counting Sort


8. Radix Sort


9. Bucket Sort


🧠 Stability in Sorting

Algorithm Stable
Bubble Sort βœ…
Selection Sort ❌
Insertion Sort βœ…
Merge Sort βœ…
Quick Sort ❌
Heap Sort ❌
Counting Sort βœ…
Radix Sort βœ…

πŸ“Š When to Use What?

Case Use
Small dataset, nearly sorted Insertion Sort
Large dataset, consistent performance Merge Sort
Space is a concern Quick Sort, Heap Sort
Sorting integers in a known small range Counting Sort, Radix Sort
Need stable sorting Merge Sort, Insertion Sort

πŸ§ͺ Benchmarking Tips


<< back to Guides