Skip to content

Sorting Algorithms

Key sorting algorithms: QuickSort (O(n log n) avg, in-place, unstable), MergeSort (O(n log n) guaranteed, stable, extra space), HeapSort (O(n log n), in-place). Java's Arrays.sort() uses TimSort (merge+insertion) for objects, dual-pivot QuickSort for primitives. Know when to use each and their trade-offs.

Key Concepts

Deep Dive: Comparison of Sorting Algorithms
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)
Counting Sort O(n+k) O(n+k) O(n+k) O(k)
Deep Dive: Quick Sort
public void quickSort(int[] arr, int low, int high) {
    if (low < high) {
        int pivotIndex = partition(arr, low, high);
        quickSort(arr, low, pivotIndex - 1);
        quickSort(arr, pivotIndex + 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) {
            i++;
            swap(arr, i, j);
        }
    }
    swap(arr, i + 1, high);
    return i + 1;
}
Deep Dive: Merge Sort
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 = new int[right - left + 1];
    int i = left, j = mid + 1, k = 0;
    while (i <= mid && j <= right) {
        if (arr[i] <= arr[j]) temp[k++] = arr[i++];
        else temp[k++] = arr[j++];
    }
    while (i <= mid) temp[k++] = arr[i++];
    while (j <= right) temp[k++] = arr[j++];
    System.arraycopy(temp, 0, arr, left, temp.length);
}
Common Interview Questions
  • Sort an array (implement quicksort or mergesort)
  • Sort Colors (Dutch National Flag — 3-way partition)
  • Merge Intervals
  • Largest Number (custom comparator)
  • When would you choose merge sort over quick sort?
  • What is a stable sort? Why does it matter?