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 is only a few lines:

        int n = names.length; 
while (n > 1) {
for (int j = 0; j < n - 1; j++) {
if (names[j].compareTo(names[j + 1]) > 0) {
final String 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 first iteration. Subsequent iterations will be shorter and, therefore, the variable n will be decreased.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151