Really not getting the bubble sort, which can be called a sinking sort more appropriately since it's actually sinking the bigger/heavier to the bottom as the majority of the answers presented. One of the most typicals will be
private static void sortZero(Comparable[] arr) {
boolean moreSinkingRequired = true;
while (moreSinkingRequired) {
moreSinkingRequired = false;
for (int j = 0; j < arr.length - 1; ++j) {
if (less(arr, j + 1, j)) {
exch(arr, j, j + 1);
moreSinkingRequired = true;
}
}
}
}
By the way, you have to traverse once more than actually required to stop earlier.
But as I see it bubbling as
private static void sortOne(Comparable[] arr) {
for (int i = 0; i < arr.length - 1; ++i) {
for (int j = arr.length - 1; j > i; --j) { // start from the bottom
if (less(arr, j, j - 1)) {
exch(arr, j - 1, j);
}
}
}
}
You have to know this method is actually better since it's tracking the end point for comparison by j > i with [0, i-1] already sorted.
We also can add earlier termination but it then becomes verbose as
private static void sortTwo(Comparable[] arr) {
boolean moreBubbleRequired = true;
for (int i = 0; i < arr.length - 1 && moreBubbleRequired; ++i) {
moreBubbleRequired = false;
for (int j = arr.length - 1; j > i; --j) {
if (less(arr, j, j - 1)) {
exch(arr, j - 1, j);
moreBubbleRequired = true;
}
}
}
}
The utils used to make the process terse are
public static boolean less(Comparable[] arr, int i, int j) {
return less(arr[i], arr[j]);
}
public static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}
public static void exch(Comparable[] arr, int i, int j) {
Comparable t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
java.util.Arrayswould be useless if it were so.