Sorting in Real Java Code

Don't write your own sort at work

Writing sorts teaches you how they work. In real programs, use Java's built-in ones – they're fast (O(n log n)) and well tested:

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

public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 45, 90, 61, 88};
        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));

        String[] names = {"Zoya", "adam", "Bilal", "Chen"};
        Arrays.sort(names);                       // capitals come before small letters!
        System.out.println(Arrays.toString(names));

        ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(5, 2, 9, 1));
        Collections.sort(list);
        System.out.println(list);
        Collections.sort(list, Collections.reverseOrder());   // biggest first
        System.out.println(list);

        int[] part = {9, 8, 7, 6, 5, 4};
        Arrays.sort(part, 1, 4);                  // sort only indexes 1, 2, 3
        System.out.println(Arrays.toString(part));
    }
}

Output

[45, 61, 72, 88, 90]
[Bilal, Chen, Zoya, adam]
[1, 2, 5, 9]
[9, 5, 2, 1]
[9, 6, 7, 8, 5, 4]

Common mistake: Arrays.sort(intArray, Collections.reverseOrder()) does not compile – reverse order needs objects (Integer[]), not int[]. A simple fix: sort normally and read the array backwards.

Remember: Strings sort by character codes: all capital letters come before all small letters. Use String.CASE_INSENSITIVE_ORDER if you want “adam” among the A's.

In Module 9 you'll learn how the fast sorts work, and how to sort your own objects with a Comparator.

HOME LABS COMMUNITY DASHBOARD