Sorting in Miranda
Our example demonstrates sorting in Java using the Collections
class from the java.util
package. We’ll look at sorting for built-in types first.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Sorting {
public static void main(String[] args) {
// Sorting functions work for any Comparable type in Java.
// This includes many built-in types like String and Integer.
List<String> strs = new ArrayList<>();
strs.add("c");
strs.add("a");
strs.add("b");
Collections.sort(strs);
System.out.println("Strings: " + strs);
// An example of sorting integers.
List<Integer> ints = new ArrayList<>();
ints.add(7);
ints.add(2);
ints.add(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 implement our own.
private 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, compile it and then use java
:
$ javac Sorting.java
$ java Sorting
Strings: [a, b, c]
Ints: [2, 4, 7]
Sorted: true
In this Java version, we use the Collections.sort()
method to sort our lists. This method works with any list of Comparable
objects, which includes many built-in Java types like String
and Integer
.
Unlike in the original example, Java doesn’t have a built-in method to check if a list is sorted. So, we’ve implemented our own isSorted()
method that checks if the list is in ascending order.
The Collections.sort()
method sorts the list in-place, modifying the original list rather than returning a new sorted list. This is similar to the behavior of the slices.Sort()
function in the original example.
Java’s sorting algorithm is typically a modified quicksort, which offers O(n log n) performance on average. For primitive types, it uses a dual-pivot Quicksort, and for object types, it uses Timsort, which is a hybrid sorting algorithm derived from merge sort and insertion sort.