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.
To run the program:
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.