← Back to course: Java from scratch

Sorting, searching and week 4 review

Video coming soon

Storing data in arrays and lists is only half the job; almost always afterwards you need to sort them and find something inside. In this lesson you will see how to do it with the tools of the standard library and also how the simplest algorithms work inside, because understanding the logic will make you a better programmer even if in daily work you use the ready-made functions. We end with a review of the whole week.

Sorting with the standard library

Arrays.sort sorts an array in place, from smallest to largest for numbers and alphabetically for text. With lists you use Collections.sort(list) or the list.sort(null) method. When you need another criterion, for example ordering words by length or from largest to smallest, you pass a Comparator, an object that says how to compare two elements. Comparator.comparing(...) builds one from a function, reversed() flips the order and thenComparing adds a tie-break criterion. If you sort your own objects, the Comparator is essential, and you will use it a lot.

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {42, 7, 19, 3, 25};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));   // [3, 7, 19, 25, 42]

        List<String> words = new ArrayList<>(List.of("pear", "fig", "banana", "kiwi", "apple"));
        Collections.sort(words);
        System.out.println(words);        // [apple, banana, fig, kiwi, pear]

        words.sort(Comparator.comparing(String::length));
        System.out.println(words);        // [fig, kiwi, pear, apple, banana]

        words.sort(Comparator.comparing(String::length).reversed()
                             .thenComparing(Comparator.naturalOrder()));
        System.out.println(words);        // [banana, apple, kiwi, pear, fig]

        Collections.reverse(words);
        System.out.println(words);        // [fig, pear, kiwi, apple, banana]
    }
}

Searching: linear and binary

Linear search walks through the elements one by one until it finds the wanted one; it always works, even with unsorted data, but in a list of a million elements it may make a million comparisons. Binary search requires the data to be sorted: it compares with the middle element and discards half at each step, so a million elements are solved in about twenty comparisons. Java offers it in Arrays.binarySearch and Collections.binarySearch; if the value is not found it returns a negative number. Here we program it by hand so you see the idea, and also a bubble sort, slow but very instructive.

java
import java.util.Arrays;

public class Main {
    // Returns the index of target or -1. The array must be sorted.
    static int binarySearch(int[] data, int target) {
        int low = 0;
        int high = data.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (data[mid] == target) return mid;
            if (data[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }

    // Bubble sort: swap neighbours until nothing changes
    static void bubbleSort(int[] data) {
        boolean swapped = true;
        while (swapped) {
            swapped = false;
            for (int i = 0; i < data.length - 1; i++) {
                if (data[i] > data[i + 1]) {
                    int temp = data[i];
                    data[i] = data[i + 1];
                    data[i + 1] = temp;
                    swapped = true;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] data = {42, 7, 19, 3, 25};
        bubbleSort(data);
        System.out.println(Arrays.toString(data));          // [3, 7, 19, 25, 42]
        System.out.println(binarySearch(data, 25));         // 3
        System.out.println(binarySearch(data, 8));          // -1
        System.out.println(Arrays.binarySearch(data, 19));  // 2
    }
}

Week 4 review

  • Array: fixed size, indexes from 0, length without parentheses, ArrayIndexOutOfBoundsException if you go out.
  • b = a copies the reference; to copy the content use Arrays.copyOf.
  • ArrayList<Integer>: dynamic size, add, get, set, remove, size, contains; wrapper classes only.
  • remove(int) deletes by position and remove(Object) by value; do not modify the list inside a for-each.
  • Arrays.sort, Collections.sort and Comparator to sort; binary search only on sorted data.

Test what you learned

Question 1 of 6

What requirement does binary search have?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →