Outer do-while-loop repeats the passes through the array until all the elements are in the correct order, and inner for-loop passes through the array and compares adjacent elements.
public static void bubbleSort(int[] arr) {
boolean swapped;
// repeat the passes through the array until
// all the elements are in the correct order
do {
swapped = false;
// pass through the array and
// compare adjacent elements
for (int i = 0; i < arr.length - 1; i++) {
// if this element is greater than
// the next one, then swap them
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
// if there are no swapped elements at the
// current pass, then this is the last pass
} while (swapped);
}
public static void main(String[] args) {
int[] arr = {6, 1, 5, 8, 4, 3, 9, 2, 0, 7};
System.out.println(Arrays.toString(arr));
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
Output:
[6, 1, 5, 8, 4, 3, 9, 2, 0, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
See also: Bubble sort with step-by-step output • Java 8