Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 9 – Sorting

Part 1 – Sorting algorithms

Use this helper in all the sorts:

static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

Task 1 – Bubble sort

Compare neighbours and swap them when they are out of order; each pass moves the largest remaining element to the end. Stop as soon as a whole pass makes no swap.

static void bubbleSort(int[] a) { /* ToDo */ }
Solution
static void bubbleSort(int[] a) {
    for (int p = 0; p < a.length - 1; p++) {
        boolean swapped = false;
        for (int j = 0; j < a.length - 1 - p; j++)
            if (a[j] > a[j + 1]) {
                swap(a, j, j + 1);
                swapped = true;
            }
        if (!swapped)
            return;                  // no swap in a whole pass: sorted
    }
}

Task 2 – Selection sort

For each position i, find the smallest element of a[i..] and swap it into place.

static void selectionSort(int[] a) { /* ToDo */ }
Solution
static void selectionSort(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
        int min = i;
        for (int j = i + 1; j < a.length; j++)
            if (a[j] < a[min])
                min = j;
        swap(a, i, min);             // the smallest of a[i..] goes to i
    }
}

Task 3 – Insertion sort

Insert a[i] into the sorted prefix a[0..i-1], shifting the larger elements one place right. Count the comparisons in a static counter (needed in Task 5).

static long comparisons;
static void insertionSort(int[] a) { /* ToDo */ }
Solution
static long comparisons;             // counted for Task 5

static void insertionSort(int[] a) {
    for (int i = 1; i < a.length; i++) {
        int v = a[i];
        int j = i - 1;
        while (j >= 0) {
            comparisons++;
            if (a[j] <= v) break;
            a[j + 1] = a[j];         // shift the larger element right
            j--;
        }
        a[j + 1] = v;
    }
}

Task 4 – Merge sort

Sort the two halves recursively, then merge them through a temporary array.

🚩 Take from the left half when the keys are equal (<=): this keeps the sort stable.

static void mergeSort(int[] a, int lo, int hi) { /* ToDo */ }
static void merge(int[] a, int lo, int mid, int hi) { /* ToDo */ }
Solution
static void mergeSort(int[] a, int lo, int hi) {
    if (lo >= hi)
        return;                      // 0 or 1 element
    int mid = (lo + hi) / 2;
    mergeSort(a, lo, mid);
    mergeSort(a, mid + 1, hi);
    merge(a, lo, mid, hi);
}

static void merge(int[] a, int lo, int mid, int hi) {
    int[] t = new int[hi - lo + 1];
    int i = lo, j = mid + 1, k = 0;
    while (i <= mid && j <= hi)
        t[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];   // <= keeps it stable
    while (i <= mid) t[k++] = a[i++];
    while (j <= hi)  t[k++] = a[j++];
    System.arraycopy(t, 0, a, lo, t.length);
}

Test your sorts

The arrays are the examples of the slides; true means the four sorts agree.

int[][] tests = {{5, 1, 4, 2, 8}, {64, 25, 12, 22, 11}, {5, 2, 4, 6, 1, 3}};
for (int[] t : tests) {
    int[] a = t.clone(), b = t.clone(), c = t.clone(), d = t.clone();
    bubbleSort(a);
    selectionSort(b);
    insertionSort(c);
    mergeSort(d, 0, d.length - 1);
    System.out.println(Arrays.toString(t) + " -> " + Arrays.toString(a)
        + " " + (Arrays.equals(a, b) && Arrays.equals(a, c) && Arrays.equals(a, d)));
}

Expected output:

[5, 1, 4, 2, 8] -> [1, 2, 4, 5, 8] true
[64, 25, 12, 22, 11] -> [11, 12, 22, 25, 64] true
[5, 2, 4, 6, 1, 3] -> [1, 2, 3, 4, 5, 6] true

Task 5 – Counting comparisons

Run your insertion sort on 1000 keys that are already sorted, in reverse order, and random (use new Random(7) and nextInt(1_000_000)). Before running it, predict the counts: n−1n - 1? n(n−1)/2n(n-1)/2? about n2/4n^2/4?

Solution
int n = 1000;
int[] sorted = new int[n], reversed = new int[n];
for (int i = 0; i < n; i++) { sorted[i] = i; reversed[i] = n - i; }
int[][] inputs = {sorted, reversed, randomArray(n, 7)};
String[] names = {"sorted", "reversed", "random"};
for (int k = 0; k < 3; k++) {
    comparisons = 0;
    insertionSort(inputs[k]);
    System.out.printf("%-8s: %,d comparisons%n", names[k], comparisons);
}

Expected output:

sorted  : 999 comparisons
reversed: 499,500 comparisons
random  : 253,992 comparisons

Task 6 – Timing: quadratic against nlog⁡nn \log n

Time insertion sort, merge sort and Arrays.sort on random arrays of 10,000 to 80,000 keys (doubling each time). Warm the methods up first, as in Lab 1.

Solution
for (int rep = 0; rep < 5; rep++) {          // warm-up for the JIT compiler
    int[] w = randomArray(20_000, rep);
    insertionSort(w.clone()); mergeSort(w.clone(), 0, w.length - 1);
    Arrays.sort(w.clone());
}
for (int size = 10_000; size <= 80_000; size *= 2) {
    int[] a = randomArray(size, 1), b = a.clone(), c = a.clone();
    long t0 = System.nanoTime();
    insertionSort(a);
    long t1 = System.nanoTime();
    mergeSort(b, 0, b.length - 1);
    long t2 = System.nanoTime();
    Arrays.sort(c);
    long t3 = System.nanoTime();
    System.out.printf("n = %6d  insertion %8.1f ms  merge %6.1f ms  Arrays.sort %5.1f ms%n",
            size, (t1 - t0) / 1e6, (t2 - t1) / 1e6, (t3 - t2) / 1e6);
}

Sample output (your times will differ):

n =  10000  insertion     32.4 ms  merge    1.9 ms  Arrays.sort   4.2 ms
n =  20000  insertion    128.7 ms  merge    4.4 ms  Arrays.sort   8.2 ms
n =  40000  insertion    565.1 ms  merge   16.9 ms  Arrays.sort   7.1 ms
n =  80000  insertion   1850.8 ms  merge   17.7 ms  Arrays.sort  13.0 ms

When nn doubles, insertion sort takes about 4 times longer; merge sort a little more than 2 times. At n=80 000n = 80\,000 insertion sort is already about 100 times slower.

Part 2 – Use the JDK

Challenge 1 – Sorting objects, and stability

Sort the students Omar 90, Sara 85, Ali 90, Huda 78, Badr 85 by name, then by grade from highest to lowest. Because the JDK’s object sort is stable, students with equal grades stay in name order. Then get the same result in one sort with comparingInt(...).thenComparing(...), by increasing grade this time.

Solution
record Student(String name, int grade) {
    public String toString() { return name + " " + grade; }
}
List<Student> st = new ArrayList<>(List.of(
    new Student("Omar", 90), new Student("Sara", 85), new Student("Ali", 90),
    new Student("Huda", 78), new Student("Badr", 85)));

st.sort(Comparator.comparing(Student::name));          // by name
System.out.println(st);
st.sort(Comparator.comparingInt(Student::grade).reversed());
System.out.println(st);     // stable: equal grades stay in name order

st.sort(Comparator.comparingInt(Student::grade)        // the same in one go
                  .thenComparing(Student::name));
System.out.println(st);

Expected output:

[Ali 90, Badr 85, Huda 78, Omar 90, Sara 85]
[Ali 90, Omar 90, Badr 85, Sara 85, Huda 78]
[Huda 78, Badr 85, Sara 85, Ali 90, Omar 90]

Challenge 2 – Merge overlapping intervals

Merge [8,10] [1,3] [15,18] [2,6] [9,12]. After sorting by start, an interval overlaps the current group exactly when it starts before the group ends: one pass is enough, so the whole solution is O(nlog⁡n)O(n \log n).

Solution
static List<int[]> mergeIntervals(int[][] iv) {
    Arrays.sort(iv, Comparator.comparingInt(x -> x[0]));   // by start
    List<int[]> res = new ArrayList<>();
    int[] cur = iv[0].clone();
    for (int[] x : iv) {
        if (x[0] <= cur[1])                     // overlaps the current group
            cur[1] = Math.max(cur[1], x[1]);
        else {
            res.add(cur);
            cur = x.clone();
        }
    }
    res.add(cur);
    return res;
}
int[][] iv = {{8, 10}, {1, 3}, {15, 18}, {2, 6}, {9, 12}};
for (int[] x : mergeIntervals(iv))
    System.out.print(Arrays.toString(x) + " ");
System.out.println();

Expected output:

[1, 6] [8, 12] [15, 18] 

Challenge 3 – Sorting strings

Sort pear fig banana kiwi apple date alphabetically, then by length (and alphabetically for equal lengths). Then write anagrams(s, t): two words are anagrams exactly when their sorted letters are equal.

Solution
static boolean anagrams(String s, String t) {
    char[] a = s.toCharArray(), b = t.toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    return Arrays.equals(a, b);
}
String[] words = {"pear", "fig", "banana", "kiwi", "apple", "date"};
String[] w = words.clone();
Arrays.sort(w);                                         // alphabetical
System.out.println(Arrays.toString(w));
Arrays.sort(w, Comparator.comparingInt(String::length)  // by length, then
                         .thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(w));
System.out.println(anagrams("listen", "silent") + " " + anagrams("apple", "paper"));

Expected output:

[apple, banana, date, fig, kiwi, pear]
[fig, date, kiwi, pear, apple, banana]
true false