Skip to lesson

Practice: sorting

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Solve essential sorting challenges: Dutch National Flag, frequency sorting, and in-place merging.

The Dutch National Flag Problem

The Dutch National Flag problem sorts values 0, 1 and 2. The programs below go from sorting, to counting, to one pass with three pointers.

Example 1 · Brute force: sort the array (O(n log n) time, O(1) extra space)

DutchSortBrute.javaJava
import java.util.Arrays;
public class DutchSortBrute {    public static void main(String[] args) {        int[] nums = {2, 0, 2, 1, 1, 0};        Arrays.sort(nums);        System.out.println(Arrays.toString(nums));    }}
Output
[0, 0, 1, 1, 2, 2]

What this code does

  • Arrays.sort works but ignores that there are only three different values.
  • A general sort costs n log n comparisons, more than this problem needs.

Example 2 · Better: count each value, then rewrite (O(n) time, O(1) space, two passes)

DutchCounting.javaJava
import java.util.Arrays;
public class DutchCounting {    public static void sortColors(int[] nums) {        int[] count = new int[3];        for (int x : nums) {            count[x]++;        }        int k = 0;        for (int value = 0; value < 3; value++) {            for (int c = 0; c < count[value]; c++) {                nums[k++] = value;            }        }    }
    public static void main(String[] args) {        int[] nums = {2, 0, 2, 1, 1, 0};        sortColors(nums);        System.out.println(Arrays.toString(nums));    }}
Output
[0, 0, 1, 1, 2, 2]

What this code does

  • One pass counts the 0s, 1s and 2s, and a second pass writes them back in order.
  • Linear time, but the array is read and written twice.

Example 3 · Optimal: one pass with three pointers (O(n) time, O(1) space)

SortColorsDemo.javaJava
import java.util.Arrays;
public class SortColorsDemo {    public static void sortColors(int[] nums) {        int low = 0, mid = 0, high = nums.length - 1;        while (mid <= high) {            if (nums[mid] == 0) {                int temp = nums[low];                nums[low] = nums[mid];                nums[mid] = temp;                low++;                mid++;            } else if (nums[mid] == 1) {                mid++;            } else {                int temp = nums[mid];                nums[mid] = nums[high];                nums[high] = temp;                high--;            }        }    }
    public static void main(String[] args) {        int[] nums = {2, 0, 2, 1, 1, 0};        sortColors(nums);        System.out.println(Arrays.toString(nums));    }}
Output
[0, 0, 1, 1, 2, 2]

What this code does

  • One scan puts every 0 before low, every 2 after high and leaves the 1s in the middle, so nothing is sorted or counted twice.
  • Maintains three pointers low, mid, and high.
  • Swaps 0 to the low boundary and advances both low and mid.
  • Advances mid when encountering 1, keeping 1s in the middle.

Standard comparison sorting takes O(n log n) time. Counting sort requires two passes and extra array storage. Edsger Dijkstra designed the Dutch National Flag algorithm to sort three keys in one in-place pass. The algorithm maintains three pointers: low, mid, and high. The array is partitioned into four zones during execution. Indices from 0 to low - 1 contain 0s. Indices from low to mid - 1 contain 1s. Indices from mid to high are uninspected elements. Indices from high + 1 to n - 1 contain 2s. The pointer mid scans through the uninspected zone. If arr[mid] == 0, swap arr[low] and arr[mid], increment both low and mid. If arr[mid] == 1, increment mid. If arr[mid] == 2, swap arr[mid] and arr[high], decrement high without advancing mid. The algorithm terminates when mid exceeds high, running in O(n) time and O(1) memory.

Trace the code

Trace the three pointers

public class FlagTrace {
public static void main(String[] args) {
int[] nums = {2, 0, 1, 2, 0};
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 {
swap(nums, mid, high--);
}
}
System.out.println(java.util.Arrays.toString(nums));
}
static void swap(int[] a, int i, int j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
}

Variables

nums
[2, 0, 1, 2, 0]
low
0
mid
0
high
4

Output

(nothing printed yet)

Line 4The three pointers start at both ends. Values before low are 0, values after high are 2.

Step 1 of 7

In-Place Merging and Frequency Sorting

Two sorted arrays can be merged in place by writing from the back, and characters can be sorted by how often they occur. The examples show both.

Example 4 · Brute force: copy both arrays together and sort (O((m + n) log (m + n)) time)

MergeInPlaceBrute.javaJava
import java.util.Arrays;
public class MergeInPlaceBrute {    public static void merge(int[] nums1, int m, int[] nums2, int n) {        for (int i = 0; i < n; i++) {            nums1[m + i] = nums2[i];        }        Arrays.sort(nums1);    }
    public static void main(String[] args) {        int[] nums1 = {1, 2, 3, 0, 0, 0};        int[] nums2 = {2, 5, 6};        merge(nums1, 3, nums2, 3);        System.out.println(Arrays.toString(nums1));    }}
Output
[1, 2, 2, 3, 5, 6]

What this code does

  • The second array is copied into the empty slots, and the whole array is sorted again.
  • It throws away the fact that both inputs were already sorted.

Example 5 · Optimal: merge from the back (O(m + n) time, O(1) space)

MergeInPlaceDemo.javaJava
import java.util.Arrays;
public class MergeInPlaceDemo {    public static void merge(int[] nums1, int m, int[] nums2, int n) {        int p1 = m - 1;        int p2 = n - 1;        int p = m + n - 1;
        while (p1 >= 0 && p2 >= 0) {            if (nums1[p1] > nums2[p2]) {                nums1[p--] = nums1[p1--];            } else {                nums1[p--] = nums2[p2--];            }        }        while (p2 >= 0) {            nums1[p--] = nums2[p2--];        }    }
    public static void main(String[] args) {        int[] nums1 = {1, 2, 3, 0, 0, 0};        int[] nums2 = {2, 5, 6};        merge(nums1, 3, nums2, 3);        System.out.println(Arrays.toString(nums1));    }}
Output
[1, 2, 2, 3, 5, 6]

What this code does

  • Writing from the back never overwrites an unread value, so no buffer and no second sort are needed.
  • Initializes pointers at the tails of valid data in both arrays.
  • Initializes write pointer at the final index of nums1 buffer.
  • Places the larger remaining element at write pointer moving backwards.

Example 6 · Sort characters by frequency with buckets (O(n) time, O(n) space)

FrequencySortDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class FrequencySortDemo {    public static String frequencySort(String s) {        Map<Character, Integer> counts = new HashMap<>();        for (char c : s.toCharArray()) {            counts.put(c, counts.getOrDefault(c, 0) + 1);        }
        List<Character>[] buckets = new List[s.length() + 1];        for (int i = 0; i <= s.length(); i++) buckets[i] = new ArrayList<>();
        for (Map.Entry<Character, Integer> entry : counts.entrySet()) {            buckets[entry.getValue()].add(entry.getKey());        }
        StringBuilder sb = new StringBuilder();        for (int f = s.length(); f >= 1; f--) {            for (char c : buckets[f]) {                for (int i = 0; i < f; i++) sb.append(c);            }        }        return sb.toString();    }
    public static void main(String[] args) {        String s = "tree";        System.out.println("Frequency sorted: " + frequencySort(s));    }}
Output
Frequency sorted: eert

What this code does

  • Counts frequency of each character using a hash map.
  • Creates frequency buckets from 1 to s.length().
  • Groups characters with identical frequencies into matching buckets.

Array 1 has size m + n. The first m slots hold values, and n slots remain empty. Merging from the front overwrites unread elements in array 1. Moving elements right takes quadratic O(m * n) time. Instead, merge from back to front using three pointers. Place p1 at m - 1 and p2 at n - 1. Set write pointer p at m + n - 1. Compare arr1[p1] and arr2[p2], placing the larger value at index p and decrementing. Because free slots sit at the end, write operations never overwrite unread elements. This in-place merge runs in linear O(m + n) time and O(1) auxiliary space. Frequency sorting orders elements by their frequency of occurrence. First, a hash map counts frequencies in linear O(n) time. Next, an array of buckets indexed from 1 to n groups characters by frequency. Scanning buckets from n down to 1 rebuilds the string in O(n) time. This avoids comparison sorting, achieving optimal linear time.

Choosing the Right Sort in Production

Selecting the right sorting algorithm depends on data size, memory, and stability requirements. For small arrays with fewer than 40 elements, insertion sort has the lowest overhead. Its compact loops and zero function calls maximize CPU hardware performance. For large primitive arrays in memory, Dual-Pivot Quicksort delivers maximum cache locality.

When sorting multi-attribute objects where stability matters, TimSort is the standard choice. TimSort preserves equal-key order and runs in linear time on pre-sorted runs. When key ranges are small integers, counting sort runs in pure linear O(n + k) time. Examples include student test scores, age distributions, and product ratings.

For data too large to fit in RAM, external merge sort is required. It sorts manageable chunks in memory, writes them to disk, and merges sorted streams. Understanding these algorithmic trade-offs ensures optimal system performance. Always match the sorting algorithm to your specific data characteristics.

Finish up

Mark complete & continue

Next: Trees and tree words