Skip to lesson

Why sorting matters

Sorting organizes unordered data into ascending or descending sequence. It serves as a foundational preprocessing step that simplifies complex algorithms.

Sorted data enables binary search and two pointers

Sorting is arranging elements in order, such as smallest to largest. Many problems become easier once the data is sorted.

Sorting once unlocks binary search and two pointers. The programs below find a value and a pair after sorting, and the first one tries every pair instead.

  1. Identify whether the problem involves repeated searches or pair combinations.
  2. Sort the dataset in ascending order in O(n log n) time.
  3. Apply binary search or two pointers to solve the query in O(log n) or O(n) time.

Example 1 · Binary Search Enabled by Sorting

BinarySearchAfterSortDemo.javaJava
import java.util.Arrays;
public class BinarySearchAfterSortDemo {    public static void main(String[] args) {        int[] nums = {9, 1, 4, 3, 7};        Arrays.sort(nums); // Becomes [1, 3, 4, 7, 9]
        int target = 7;        int idx = Arrays.binarySearch(nums, target);
        System.out.println("Sorted: " + Arrays.toString(nums));        System.out.println("Target " + target + " found at index: " + idx);    }}
Output
Sorted: [1, 3, 4, 7, 9]
Target 7 found at index: 3

What this code does

  • Arrays.sort arranges numbers in ascending order in O(n log n) time.
  • binarySearch checks middle element and converges in O(log n) time.
  • Target 7 is located at index 3 in only 2 comparisons.

Example 2 · Brute force: check every pair (O(n²) time, O(1) space)

PairSumBrute.javaJava
public class PairSumBrute {    public static boolean hasPairSum(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    return true;                }            }        }        return false;    }
    public static void main(String[] args) {        int[] arr = {8, 3, 1, 6, 2};        System.out.println("Pair for 9: " + hasPairSum(arr, 9));        System.out.println("Pair for 20: " + hasPairSum(arr, 20));    }}
Output
Pair for 9: true
Pair for 20: false

What this code does

  • Two loops add every pair of values and compare the sum with the target.
  • With n values there are n × (n - 1) / 2 pairs, so the work grows with the square of n.

Example 3 · Optimal: sort, then two pointers (O(n log n) time, O(1) extra space)

TwoPointersAfterSortDemo.javaJava
import java.util.Arrays;
public class TwoPointersAfterSortDemo {    public static boolean hasPairSum(int[] nums, int target) {        Arrays.sort(nums);        int left = 0, right = nums.length - 1;        while (left < right) {            int sum = nums[left] + nums[right];            if (sum == target) return true;            if (sum < target) left++;            else right--;        }        return false;    }
    public static void main(String[] args) {        int[] arr = {8, 3, 1, 6, 2};        System.out.println("Pair for 9: " + hasPairSum(arr, 9));        System.out.println("Pair for 20: " + hasPairSum(arr, 20));    }}
Output
Pair for 9: true
Pair for 20: false

What this code does

  • After sorting, a sum that is too small moves left up and one that is too large moves right down, so each value is visited once instead of paired with every other value.
  • Sorting array into [1, 2, 3, 6, 8] enables two pointers.
  • Pointers move inward in O(n) time based on sum comparisons.
  • 1 + 8 = 9 returns true; pair for 20 returns false.

Searching an item in an unsorted list of one million elements requires one million checks. Finding pairs that sum to a target requires checking all pairs in slow quadratic O(n²) time. Sorting the data first transforms the problem, unlocking logarithmic and linear operations. Once an array is sorted, binary search locates any element in O(log n) time. For one million elements, binary search requires at most twenty comparisons instead of one million. Two-pointer algorithms can then find matching pairs by moving inward from both ends in linear O(n) time. Sorting pays an initial O(n log n) cost that accelerates all subsequent queries. Consider searching for value 7 in unsorted array [9, 1, 4, 3, 7]. Linear search checks indices 0, 1, 2, 3, and 4, taking 5 comparisons. Now sort the array into [1, 3, 4, 7, 9]. Binary search checks index 2 (value 4). Since 7 > 4, it checks index 3 (value 7) and succeeds in 2 steps.

  • Preprocessing benefit: pay O(n log n) once to answer repeated queries in O(log n).
  • Binary search: halves search space at every step on sorted collections.
  • Two pointers: converges inward in O(n) time to find target pair sums.

Comparison sorts and theoretical limits

Comparison sorts determine relative order strictly by comparing pairs of elements. Algorithms like bubble sort, merge sort, and quicksort make decisions using comparisons. Each comparison yields one bit of information, answering whether an item is smaller. To sort n distinct elements, the algorithm must identify the correct ordering.

A binary decision tree models all comparison outcomes for an input of size n. The tree must contain at least n factorial leaves to distinguish every permutation. The minimum tree height is therefore log₂(n factorial), which is proportional to n log n. Consequently, no comparison-based sort can beat O(n log n) in the worst case.

Trace a decision tree for three elements [A, B, C]: There are 3 * 2 * 1 = 6 possible permutations. First compare A and B: if A < B, we eliminate three permutations immediately. Next compare B and C, then A and C to isolate the unique sorted order. At least three comparisons are required to identify the correct arrangement among six possibilities.

  • Comparison sort: determines relative order strictly through element comparisons.
  • Information theoretic lower bound: comparison sorting requires at least Omega(n log n) steps.
  • Universal applicability: comparison sorts work on any type implementing Comparable.

Stability in sorting algorithms

Stability is the property of a sort that keeps items with equal keys in the same order they had before sorting.

A stable sort keeps equal keys in their original order. The example sorts students by score and shows that equal scores stay in input order.

Example 4 · Demonstrating Stability with Object Keys

StableSortDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class StableSortDemo {    static class Student {        String name;        int score;        Student(String n, int s) { name = n; score = s; }        public String toString() { return name + ":" + score; }    }
    public static void main(String[] args) {        List<Student> list = new ArrayList<>();        list.add(new Student("Alice", 90));        list.add(new Student("Bob", 80));        list.add(new Student("Charlie", 90));
        // TimSort (List.sort) is guaranteed stable        list.sort(Comparator.comparingInt(s -> s.score));
        System.out.println(list);    }}
Output
[Bob:80, Alice:90, Charlie:90]

What this code does

  • Bob with score 80 moves to index 0.
  • Alice and Charlie share score 90 and preserve original arrival order.
  • Alice remains ahead of Charlie, proving sort stability.

Suppose a table of students is initially sorted alphabetically by student name. Sorting the table with an unstable sort can reorder students who have identical test scores. A stable sort guarantees that students with identical scores retain their original alphabetical sequence. Stability is essential when sorting datasets by multiple attributes in sequential passes. For example, sorting by city first and then by state preserves city groupings within each state. Merge sort and insertion sort are inherently stable. In contrast, standard quicksort and heap sort are unstable because distant swaps disrupt original order. Trace stable sorting on items with equal keys: Input pairs: [("Alice", 90), ("Bob", 80), ("Charlie", 90)]. Sort by score using a stable sort: ("Bob", 80) moves to index 0 because 80 < 90. Equal score items ("Alice", 90) and ("Charlie", 90) retain relative order: Alice remains before Charlie! Result is [("Bob", 80), ("Alice", 90), ("Charlie", 90)].

  • Stable sort: equal keys preserve their initial relative positions.
  • Unstable sort: equal keys may be reordered arbitrarily during partitioning or swapping.
  • Multi-level sorting: stable sorts enable sorting by column B then column A cleanly.

Predict the output

Predict the stable order

Read the snippet and pick what it prints.

List<String> names = new ArrayList<>(List.of("Alice:90", "Bob:80", "Charlie:90"));
names.sort(Comparator.comparingInt(s -> Integer.parseInt(s.substring(s.indexOf(':') + 1))));
System.out.println(names);

Next step

Check your understanding

10 quick questions