Example. Bubble sort

[comp1110-1Z]

Bubble sort swaps a lot of elements, but the key idea is that once it finds the maximum element in the unsorted part of the array, it keeps "bubbling" it up further and further, until we reach the end of the unsorted part, where a sorted array of elements larger than the new element is waiting. In that sense, it works like selection sort (either one of them could also just work in the other direction), but with more elements being moved around. We include the "early exit" trick mentioned by Definition [comp1110-1X]:

void bubbleSort(int[] arr) { int i = arr.length - 1; while(i > 0) { // INV: arr[i..arr.length-1] is sorted, and // for every j in [0..i], arr[j] <= every element // in arr[i+1..arr.length-1] int j = 0; boolean swapped = false; while(j < i) { // INV: for every k < j, arr[k] < arr[j] // and if swapped == false, then arr[0..j-1] is sorted if(arr[j] > arr[j + 1]) { int swap = arr[j]; arr[j] = arr[j + 1]; arr[j+1] = swap; swapped = true; } j = j + 1; } // for every k < i, arr[k] < arr[i], and if // swapped == false, then arr[0..i-1] is sorted if(!swapped) { // at this point, both arr[0..i-1] and arr[i..arr.length-1] // are sorted, and we know that every element in // arr[0..i-1] is less than or equal to every element in // arr[i..arr.length-1]. hence, the whole array is sorted i = 0; } i = i - 1; } // arr[0..arr.length-1] is sorted }
bars magnifying-glass caret-down plus minus arrow-right xmark