LearnWithKiriti

Revise All 5 Sorting Algorithms

đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Bubble Sort
  3. Selection Sort
  4. Insertion Sort
  5. Merge Sort
  6. Quick Sort

Revision notes

Sort an Array

Video: “Revise All 5 Sorting Algorithms” on LearnWithKiriti (Kodee). LeetCode 912.

Return the array sorted from smallest to largest (LeetCode 912). The revision page for bubble, selection, insertion, merge and quick sort. Example: [5, 2, 3, 1] -> [1, 2, 3, 5]

Folder Sort Time Extra space
1-BubbleSort/ Bubble: the biggest bubble rises to sortedEnd each pass; stop early if a pass made no swap. O(n²) worst, O(n) if already sorted O(1)
2-SelectionSort/ Selection: select the smallest of the rest and swap it into frontSlot. O(n²) O(1)
3-InsertionSort/ Insertion: make room for the newBook by shifting bigger books right, then drop it into the gap. O(n²) worst, O(n) if almost sorted O(1)
4-MergeSort/ Merge: split in half, sort each half, merge with two pointers (leftSpot, rightSpot). O(n log n) O(n)
5-QuickSort/ Quick: partition around the last number (pivot) with a wall, then sort each side. O(n log n) on average, O(n²) worst O(log n)
Sort Time (worst) Best case Extra space Stable
Bubble O(n²) O(n) with early exit O(1) yes
Selection O(n²) O(n²) O(1) no
Insertion O(n²) O(n) O(1) yes
Merge O(n log n) O(n log n) O(n) yes
Quick O(n²) O(n log n) O(log n) no

Rebuild it from the name

Rebuild each sort from its name. Bubble: neighbours swap, the biggest bubble rises to the end. Selection: select the smallest, put it at the front. Insertion: make room, then insert one more book. Merge: split, sort the halves, merge with two pointers. Quick: partition around a pivot, then sort each side. For a big array only merge sort (and quick sort on average) is O(n log n); the other three are O(n²).

Each folder has the same code as that sort’s own page, returning nums as LeetCode 912 asks. Every program sorts [5, 2, 3, 1] (the part under “Run it locally”); the solution itself is the same code as the practice panel’s Start menu on learnwithkiriti.com.

other

Bubble Sort

Bubble sort: shrink the end, stop early

After each pass the biggest bubble rises to sortedEnd, so the next pass stops one earlier; and if a pass made no swap, the array is sorted: stop.

for sortedEnd from size - 1 down to 1:
    swapped = false
    for currBubble from 0 to sortedEnd - 1:
        nextBubble = currBubble + 1
        if nums[currBubble] > nums[nextBubble]:
            swap nums[currBubble] and nums[nextBubble]
            swapped = true
    if not swapped:
        stop            // already sorted

Dry run on [7, 2, 8, 1, 5] (the sort’s own example):

sortedEnd pass result swapped?
4 [2, 7, 1, 5, 8] yes
3 [2, 1, 5, 7, 8] yes
2 [1, 2, 5, 7, 8] yes
1 [1, 2, 5, 7, 8] no -> stop

Worst case (reversed input) still O(n²); best case (sorted) one pass, O(n). O(1) extra space. Stable: equal numbers never swap.

BubbleSort.java
class Solution {
    public int[] sortArray(int[] nums) {
        // after each pass, the biggest bubble rises to sortedEnd
        for (int sortedEnd = nums.length - 1; sortedEnd > 0; sortedEnd--) {
            boolean swapped = false;
            for (int currBubble = 0; currBubble < sortedEnd; currBubble++) {
                int nextBubble = currBubble + 1;
                if (nums[currBubble] > nums[nextBubble]) {
                    swap(nums, currBubble, nextBubble);
                    swapped = true;
                }
            }
            // a pass with no swaps means the array is already sorted
            if (!swapped) {
                break;
            }
        }
        return nums;
    }

    private void swap(int[] nums, int left, int right) {
        int held = nums[left];
        nums[left] = nums[right];
        nums[right] = held;
    }
}
other

Selection Sort

Selection sort

For each frontSlot, check every candidate in the rest, remember the smallest (smallestSpot), and swap it into frontSlot. At most n - 1 swaps: the fewest moves of the simple sorts.

for frontSlot from 0 to size - 2:
    smallestSpot = frontSlot
    for candidate from frontSlot + 1 to size - 1:
        if nums[candidate] < nums[smallestSpot]:
            smallestSpot = candidate
    if smallestSpot != frontSlot:
        swap nums[frontSlot] and nums[smallestSpot]

Dry run on [7, 2, 8, 1, 5] (the sort’s own example):

frontSlot smallestSpot (value) array after the swap
0 3 (1) [1, 2, 8, 7, 5]
1 1 (2) [1, 2, 8, 7, 5] (already in place, no swap)
2 4 (5) [1, 2, 5, 7, 8]
3 3 (7) [1, 2, 5, 7, 8]

Always about n²/2 comparisons: O(n²), even on sorted input. At most n - 1 swaps. O(1) extra space. Not stable (a swap can jump over an equal number).

SelectionSort.java
class Solution {
    public int[] sortArray(int[] nums) {
        // each pass selects the smallest of the rest and puts it at frontSlot
        for (int frontSlot = 0; frontSlot < nums.length - 1; frontSlot++) {
            int smallestSpot = frontSlot;
            for (int candidate = frontSlot + 1; candidate < nums.length; candidate++) {
                if (nums[candidate] < nums[smallestSpot]) {
                    smallestSpot = candidate;
                }
            }
            if (smallestSpot != frontSlot) {
                swap(nums, frontSlot, smallestSpot);
            }
        }
        return nums;
    }

    private void swap(int[] nums, int left, int right) {
        int held = nums[left];
        nums[left] = nums[right];
        nums[right] = held;
    }
}
other

Insertion Sort

Insertion sort: make room, then insert

Take the newBook, shift every bigger book one step right to make room, then drop newBook into the gap. One write per step.

for newBookSpot from 1 to size - 1:
    newBook = nums[newBookSpot]
    gap = newBookSpot
    while gap > 0 and nums[gap - 1] > newBook:
        nums[gap] = nums[gap - 1]     // shift right
        gap = gap - 1
    nums[gap] = newBook

Dry run on [7, 2, 8, 1, 5] (the sort’s own example):

Inserting 1 (newBookSpot = 3) into [2, 7, 8 | 1, 5]:

gap shift array
3 8 moves right [2, 7, 8, 8, 5]
2 7 moves right [2, 7, 7, 8, 5]
1 2 moves right [2, 2, 7, 8, 5]
0 stop, write newBook [1, 2, 7, 8, 5]

O(n²) worst case (reversed), O(n) best case (already sorted), great for almost-sorted data. O(1) extra space. Stable.

InsertionSort.java
class Solution {
    public int[] sortArray(int[] nums) {
        // everything left of newBookSpot is already sorted
        for (int newBookSpot = 1; newBookSpot < nums.length; newBookSpot++) {
            int newBook = nums[newBookSpot];
            int gap = newBookSpot;
            // shift every bigger book one step right to make room
            while (gap > 0 && nums[gap - 1] > newBook) {
                nums[gap] = nums[gap - 1];
                gap--;
            }
            nums[gap] = newBook;
        }
        return nums;
    }
}
other

Merge Sort

Merge sort

Split in half until each piece has one number, then merge sorted halves with two pointers (leftSpot, rightSpot), always taking the smaller front number.

mergeSort(nums):
    mergeSortHelper(nums, 0, n - 1)

mergeSortHelper(nums, low, high):
    if low >= high: return                # 0 or 1 item: already sorted
    mid = low + (high - low) / 2          # never overflows, unlike (low + high) / 2
    mergeSortHelper(nums, low, mid)
    mergeSortHelper(nums, mid + 1, high)
    merge(nums, low, mid, high)

merge(nums, low, mid, high):
    merged = empty list
    leftSpot = low, rightSpot = mid + 1
    while leftSpot <= mid and rightSpot <= high:      # both halves still have numbers
        if nums[leftSpot] <= nums[rightSpot]:         # <= keeps equal items in order (stable)
            add nums[leftSpot] to merged; leftSpot++
        else:
            add nums[rightSpot] to merged; rightSpot++
    add what is left of the left half, then of the right half (only one has leftovers)
    copy merged back into nums starting at low

O(n log n) in the best, average and worst case: log n levels of halving, each merging all n numbers once. O(n) extra space (the merged list). Stable.

MergeSort.java
class Solution {
    public int[] sortArray(int[] nums) {
        mergeSortHelper(nums, 0, nums.length - 1);
        return nums;
    }

    private void mergeSortHelper(int[] nums, int low, int high) {
        // one number is already sorted
        if (low >= high) {
            return;
        }
        int mid = low + (high - low) / 2;
        mergeSortHelper(nums, low, mid);
        mergeSortHelper(nums, mid + 1, high);
        merge(nums, low, mid, high);
    }

    private void merge(int[] nums, int low, int mid, int high) {
        int[] merged = new int[high - low + 1];
        int leftSpot = low;
        int rightSpot = mid + 1;
        int mergedSpot = 0;
        // always take the smaller front number of the two sorted halves
        while (leftSpot <= mid && rightSpot <= high) {
            if (nums[leftSpot] <= nums[rightSpot]) {
                merged[mergedSpot++] = nums[leftSpot++];
            } else {
                merged[mergedSpot++] = nums[rightSpot++];
            }
        }
        while (leftSpot <= mid) {
            merged[mergedSpot++] = nums[leftSpot++];
        }
        while (rightSpot <= high) {
            merged[mergedSpot++] = nums[rightSpot++];
        }
        System.arraycopy(merged, 0, nums, low, merged.length);
    }
}
other

Quick Sort

Quick sort (last number as pivot)

Partition around the last number (pivot): scan moves left to right, and everything ≤ pivot is swapped behind the wall. The pivot lands at the wall, then sort each side.

quickSortHelper(low, high):
    if low >= high: return
    pivotSpot = partition(low, high)
    quickSortHelper(low, pivotSpot - 1)
    quickSortHelper(pivotSpot + 1, high)

partition(low, high):
    pivot = nums[high]
    wall = low
    for scan from low to high - 1:
        if nums[scan] <= pivot:
            swap nums[wall] and nums[scan]
            wall = wall + 1
    swap nums[wall] and nums[high]
    return wall

Dry run on [7, 2, 8, 1, 5] (the sort’s own example):

partition([7, 2, 8, 1, 5]), pivot = 5:

scan value <= 5? wall after array
0 7 no 0 [7, 2, 8, 1, 5]
1 2 yes 1 [2, 7, 8, 1, 5]
2 8 no 1 [2, 7, 8, 1, 5]
3 1 yes 2 [2, 1, 8, 7, 5]
end pivot to wall [2, 1, 5, 7, 8]

5 is final; sort [2, 1] and [7, 8].

Average O(n log n); worst O(n²) when the pivot is always the smallest or biggest (sorted input with a last-number pivot). Extra space: the recursion, O(log n) on average. Not stable. A random pivot makes the worst case very unlikely.

QuickSort.java
class Solution {
    public int[] sortArray(int[] nums) {
        quickSortHelper(nums, 0, nums.length - 1);
        return nums;
    }

    private void quickSortHelper(int[] nums, int low, int high) {
        // one number is already sorted
        if (low >= high) {
            return;
        }
        int pivotSpot = partition(nums, low, high);
        quickSortHelper(nums, low, pivotSpot - 1);
        quickSortHelper(nums, pivotSpot + 1, high);
    }

    private int partition(int[] nums, int low, int high) {
        int pivot = nums[high];
        // everything left of wall is <= pivot
        int wall = low;
        for (int scan = low; scan < high; scan++) {
            if (nums[scan] <= pivot) {
                swap(nums, wall, scan);
                wall++;
            }
        }
        swap(nums, wall, high);
        return wall;
    }

    private void swap(int[] nums, int left, int right) {
        int held = nums[left];
        nums[left] = nums[right];
        nums[right] = held;
    }
}