Skip to content

Bubble Sort

Also known as sinking sort. You can imagine at every iteration the highest value sinks (or floats like a bubble) to the back.

Invariants

After \(j\) iterations, the largest \(j\) items are sorted in the last \(j\) positions.

Info

The last \(j\) positions refers to the interval \([n-j, n)\) where \(n\) is the size of the array

Implementation

Implementation

method BubbleSort(arr: array<int>)
  modifies arr
  requires arr.Length >= 1
  ensures isSorted(arr, 0, arr.Length)
  ensures multiset(arr[..]) == multiset(old(arr[..]))
{
  for i := 0 to arr.Length - 1
    // Ensures that the highest i elements are in the highest i positions in sorted order
    // This needs to be expressed as two invariants
    invariant isSorted(arr, arr.Length - i, arr.Length)
    invariant isPartition(arr, arr.Length - i)
    invariant multiset(arr[..]) == multiset(old(arr[..]))
  {
    for j := 0 to arr.Length - i - 1
      invariant isSorted(arr, arr.Length - i, arr.Length)
      invariant isPartition(arr, arr.Length - i)
      invariant forall k :: 0 <= k < j ==> arr[j] >= arr[k]
      invariant multiset(arr[..]) == multiset(old(arr[..]))
    {
      if arr[j] > arr[j + 1] {
        arr[j], arr[j + 1] := arr[j + 1], arr[j];
      }
    }
  }
}

// Returns true if the array is sorted from [start, end)
predicate isSorted(arr: array<int>, start: int, end: int)
  requires 0 <= start <= end <= arr.Length
  reads arr
{
  forall i :: start <= i < end - 1 ==> arr[i] <= arr[i + 1]
}

// Returns true if everything in the top half must be larger than everything in the bottom half
predicate isPartition(arr: array<int>, pivot: int)
  reads arr
{
  forall lower, higher :: 0 <= lower < pivot <= higher < arr.Length ==> arr[higher] >= arr[lower]
}