Sorting in Logo

Our Java program demonstrates sorting for built-in types using the Collections class. Let’s look at sorting for built-ins first.

import java.util.*;

public class Sorting {
    public static void main(String[] args) {
        // Sorting functions in Java work for any Comparable type.
        // For a list of Comparable types, see the Java documentation.
        List<String> strs = new ArrayList<>(Arrays.asList("c", "a", "b"));
        Collections.sort(strs);
        System.out.println("Strings: " + strs);

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

        // We can also use the Collections class to 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 to execute:

$ 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 lists of Comparable types. Java’s Collections class provides sorting functionality for various collection types.

Note that Java doesn’t have a built-in method to check if a list is sorted, so we implemented our own isSorted() method. This method is generic and works for any Comparable type.

The structure and functionality of the program remain similar to the original, demonstrating sorting of strings and integers, and checking if a list is sorted.