Home › Learn › Java › Arrays and lists

Sorting

Lesson 19 of 40. Put arrays and lists in order without disturbing the originals.

Arrays.sort(xs) sorts an array in place; Collections.sort(list) sorts a list in place. Both order numbers ascending and strings alphabetically (upper case before lower case, because it compares character codes). To sort without changing the caller's data, copy first: int[] copy = Arrays.copyOf(xs, xs.length) or List<String> copy = new ArrayList<>(list). Collections.reverse(list) flips a list.

Sorting is the usual first step for a median, the top few, or removing duplicates cheaply, and it is the step people forget when a result comes back in a surprising order.

int[] copy = Arrays.copyOf(xs, xs.length);
Arrays.sort(copy);
System.out.println(copy[copy.length - 1]);   // the largest

Your task

Write static int[] sortedCopy(int[] xs) returning a sorted copy, leaving xs as it was; static List<String> sortedTitles(List<String> titles) returning a new alphabetically sorted list; and static double median(int[] xs) returning the middle value of the sorted values, or the average of the two middle values when the count is even (assume at least one value).

Hint 1

int[] copy = Arrays.copyOf(xs, xs.length); Arrays.sort(copy); return copy; and the list version with new ArrayList<>(titles) and Collections.sort.

Hint 2

median: sort a copy; int mid = n / 2; odd count: copy[mid]; even: (copy[mid - 1] + copy[mid]) / 2.0.

Show the solution
import java.util.*;

public class Main {
    static int[] sortedCopy(int[] xs) {
        int[] copy = Arrays.copyOf(xs, xs.length);
        Arrays.sort(copy);
        return copy;
    }

    static List<String> sortedTitles(List<String> titles) {
        List<String> copy = new ArrayList<>(titles);
        Collections.sort(copy);
        return copy;
    }

    static double median(int[] xs) {
        int[] copy = sortedCopy(xs);
        int mid = copy.length / 2;
        if (copy.length % 2 == 1) {
            return copy[mid];
        }
        return (copy[mid - 1] + copy[mid]) / 2.0;
    }

    public static void main(String[] args) {
        System.out.println(median(new int[]{5, 1, 3}) + " " + sortedTitles(List.of("Emma", "Dune")));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.