Every developer should understand sorting algorithms — not just to use them, but to understand the trade-offs that apply to all algorithm design.
You'll rarely implement sorting from scratch — every language has a built-in. But understanding sorting teaches you:
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | ❌ |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | ✅ |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | ❌ |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | ❌ |
Repeatedly swap adjacent elements if they're in the wrong order.
public void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break; // already sorted — O(n) best case
}
}
}public void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // shift right
j--;
}
arr[j + 1] = key; // insert in correct position
}
}Java's object sorting uses Timsort, which falls back to insertion sort for small subarrays — that's why it's worth knowing.
public void mergeSort(int[] arr) {
if (arr.length <= 1) {
return;
}
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
private void merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0
public void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIdx = partition(arr, low, high);
quickSort(arr, low, pivotIdx - 1);
quickSort(arr, pivotIdx + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
In practice: Just use your language's built-in sort. Java's Arrays.sort() and Collections.sort() use Dual-Pivot Quicksort for primitives and Timsort (a hybrid of merge sort and insertion sort) for objects. Both are highly optimized for real-world data.
When values are in a known range, you can sort in linear time:
public void countingSort(int[] arr, int maxVal) {
int[] count = new int[maxVal + 1];
for (int num : arr) {
count[num]++;
}
int index = 0;
for (int val = 0; val < count.length; val++) {
while (count[val] > 0) {
arr[index++] = val;
count[val]--;
}
}
}