Sorting in Mercury

Our sorting example demonstrates how to sort different types of collections in Java. We’ll use the Collections class for sorting lists and the Arrays class for sorting arrays.

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

public class Sorting {
    public static void main(String[] args) {
        // Sorting functions in Java work with Lists and Arrays.
        // For Lists, we use the Collections class.
        // For Arrays, we use the Arrays class.

        // Sorting strings
        List<String> strs = new ArrayList<>(Arrays.asList("c", "a", "b"));
        Collections.sort(strs);
        System.out.println("Strings: " + strs);

        // Sorting integers
        List<Integer> ints = new ArrayList<>(Arrays.asList(7, 2, 4));
        Collections.sort(ints);
        System.out.println("Ints:    " + ints);

        // We can also check if a list is already in sorted order.
        boolean s = isSorted(ints);
        System.out.println("Sorted:  " + s);
    }

    // Java doesn't have a built-in method to check if a list is sorted,
    // so we'll implement our own.
    public static <T extends Comparable<? super T>> boolean isSorted(List<T> list) {
        if (list.size() <= 1) {
            return true;
        }
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i-1).compareTo(list.get(i)) > 0) {
                return false;
            }
        }
        return true;
    }
}

To run the program:

$ javac Sorting.java
$ java Sorting
Strings: [a, b, c]
Ints:    [2, 4, 7]
Sorted:  true

In this Java example, we use the Collections.sort() method to sort lists of strings and integers. Java’s sorting methods work with any class that implements the Comparable interface, which includes built-in types like String and Integer.

Unlike Go, Java doesn’t have a built-in method to check if a list is sorted, so we implemented our own isSorted method. This method uses Java’s generics to work with any type that implements Comparable.

The Collections.sort() method sorts the list in-place, modifying the original list. If you need to sort an array instead of a list, you can use Arrays.sort().

Java’s sorting algorithms are typically based on a modified mergesort or quicksort, providing a time complexity of O(n log n) for most cases.

Remember that in Java, primitive types like int need to be wrapped in their corresponding object types (like Integer) when used in collections.