Skip to main content

๐Ÿ”€ Sorting

Conceptโ€‹

Sorting is the foundation of many algorithmic patterns โ€” binary search requires sorted input, greedy interval algorithms sort by start/end, and many problems reduce to "sort then scan".

Understanding how to implement and choose the right sorting algorithm is a core interview skill.


Sorting Algorithm Comparisonโ€‹

AlgorithmBestAverageWorstSpaceStable?
Bubble SortO(n)O(nยฒ)O(nยฒ)O(1)โœ…
Selection SortO(nยฒ)O(nยฒ)O(nยฒ)O(1)โŒ
Insertion SortO(n)O(nยฒ)O(nยฒ)O(1)โœ…
Merge SortO(n log n)O(n log n)O(n log n)O(n)โœ…
Quick SortO(n log n)O(n log n)O(nยฒ)O(log n)โŒ
Heap SortO(n log n)O(n log n)O(n log n)O(1)โŒ
Counting SortO(n+k)O(n+k)O(n+k)O(k)โœ…
Radix SortO(nk)O(nk)O(nk)O(n+k)โœ…

Java's Arrays.sort() uses Dual-Pivot Quicksort for primitives and TimSort (merge + insertion) for objects.


Merge Sortโ€‹

Divide and conquer: split in half, sort each half, merge back.

public void mergeSort(int[] arr, int left, int right) {
if (left >= right) return;
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}

private void merge(int[] arr, int left, int mid, int right) {
int[] temp = Arrays.copyOfRange(arr, left, right + 1);
int i = 0, j = mid - left + 1, k = left;

while (i <= mid - left && j <= right - left) {
if (temp[i] <= temp[j]) arr[k++] = temp[i++];
else arr[k++] = temp[j++];
}
while (i <= mid - left) arr[k++] = temp[i++];
while (j <= right - left) arr[k++] = temp[j++];
}

Quick Sortโ€‹

Partition around a pivot, recursively sort sub-arrays.

public void quickSort(int[] arr, int low, int high) {
if (low >= high) return;
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}

private int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // choose last element as pivot
int i = low - 1;

for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
}
int tmp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = tmp;
return i + 1;
}

Avoiding worst case O(nยฒ): use random pivot selection:

int randomIdx = low + (int)(Math.random() * (high - low + 1));
int tmp = arr[randomIdx]; arr[randomIdx] = arr[high]; arr[high] = tmp;

Counting Sortโ€‹

Works when values are in a known, small range [0, k].

public int[] countingSort(int[] arr, int maxVal) {
int[] count = new int[maxVal + 1];
for (int n : arr) count[n]++;

// Accumulate counts (prefix sum for stability)
for (int i = 1; i <= maxVal; i++) count[i] += count[i-1];

int[] result = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
result[--count[arr[i]]] = arr[i];
}
return result;
}

Interview Application: Sort Colors (Dutch National Flag)โ€‹

Problem: Sort an array containing only 0, 1, 2 in-place in one pass.

public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;

while (mid <= high) {
if (nums[mid] == 0) {
swap(nums, low++, mid++);
} else if (nums[mid] == 1) {
mid++;
} else { // nums[mid] == 2
swap(nums, mid, high--);
// Don't increment mid! The swapped value is unexamined
}
}
}

Invariant: [0..low-1] = 0s, [low..mid-1] = 1s, [high+1..n-1] = 2s


Custom Comparator Patterns (Java)โ€‹

// Sort intervals by start time
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);

// Sort strings by length, then lexicographically
Arrays.sort(words, (a, b) -> a.length() != b.length()
? a.length() - b.length()
: a.compareTo(b));

// Sort by absolute value
Arrays.sort(arr, (a, b) -> Math.abs(a) - Math.abs(b));

// Sort 2D array by second column descending
Arrays.sort(matrix, (a, b) -> b[1] - a[1]);

// Sort strings to form largest number
Arrays.sort(strs, (a, b) -> (b + a).compareTo(a + b));

LeetCode Problemsโ€‹

๐ŸŸข Easyโ€‹

#ProblemKey Idea
217Contains DuplicateSort then check adjacent
242Valid AnagramSort strings
976Largest Perimeter TriangleSort + greedy

๐ŸŸก Mediumโ€‹

#ProblemKey Idea
56Merge IntervalsSort by start
75Sort ColorsDutch National Flag
148Sort ListMerge sort on linked list
179Largest NumberCustom comparator
252Meeting RoomsSort by start
274H-IndexSort descending
912Sort an ArrayImplement merge/quick sort

๐Ÿ”ด Hardโ€‹

#ProblemKey Idea
315Count of Smaller Numbers After SelfMerge sort with index tracking
493Reverse PairsMerge sort