Understanding the algorithm and language constructs

The algorithm was explained at the start of the chapter. The implementation is in the Sort class inside the sort() method, and it consists only of a few lines:

var n = names.length;
while (n > 1) {
    for (var j = 0; j < n - 1; j++) {
        if (names[j].compareTo(names[j + 1]) > 0) {
            final var tmp = names[j + 1];
            names[j + 1] = names[j];
            names[j] = tmp;
        }
    }
    n--;
}

The n variable holds the length of the array at the start of the sorting. Arrays in Java always have a property that gives the length, and it is called length. When we start the sorting, we will go from the start of the array to the end of it and, as you may recall, the last element, Wilson, will walk up to the last position during this ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.