Bubble Sort

Solution

Make repeated passes over the array. On each pass, compare each adjacent pair and swap the two when the left one is larger. Each pass carries the largest remaining value to the end of the unsorted part, so each pass can stop one element earlier than the last.

public static void bubbleSort(int[] arr) {
  int n = arr.length;
  for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
}
Solution
start:        4 7 2 9 1
after pass 1: 4 2 7 1 9
after pass 2: 2 4 1 7 9
after pass 3: 2 1 4 7 9
after pass 4: 1 2 4 7 9
Solution

Comparisons: in all three cases, since both loops have fixed bounds and nothing stops them early. Swaps: the number of inversions in the input, because each swap of an adjacent out-of-order pair removes exactly one. That is on a sorted array, on a reverse-sorted array, and about on a random one.

Solution
public static void bubbleSort(int[] arr) {
  int n = arr.length;
  for (int i = 0; i < n - 1; i++) {
    boolean swapped = false;
    for (int j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
        swapped = true;
      }
    }
    if (!swapped) {
      break;
    }
  }
}

Sorted: comparisons. The first pass swaps nothing and the sort stops. Reverse sorted: . Every pass swaps at least once, so the early exit never fires.

Solution

on the first: one pass carries the 5 to the end with four swaps, and a second pass of three comparisons finds nothing to swap. on the second: each pass moves the 1 only one slot to the left, so all four passes run and every comparison happens. A pass sweeps left to right, so a large element travels right in one pass but a small element travels left one slot per pass, and the number of passes is set by the element that has to go farthest left.