Repeatedly walk the array comparing adjacent pairs and swapping any that are out of order. After pass k, the k largest elements are in their final positions at the end. Stop early when a full pass makes zero swaps.

Algorithm

Canonical input [5, 1, 4, 2, 8] finishes after three passes: two with swaps, then a clean pass that triggers the early exit. Final array [1, 2, 4, 5, 8].

Basic Implementation

basic.kt
fun main() {
	val arr = intArrayOf(5, 1, 4, 2, 8)
	val n = arr.size
	for (i in 0 until n - 1) {
		var swapped = false
		for (j in 0 until n - i - 1) {
			if (arr[j] > arr[j + 1]) {
				val tmp = arr[j]
				arr[j] = arr[j + 1]
				arr[j + 1] = tmp
				swapped = true
			}
		}
		if (!swapped) {
			break
		}
	}
	println(arr.joinToString(prefix = "[", postfix = "]"))
}

Complexity

  • Time: O(n^2) worst and average; O(n) best (already sorted with early exit)
  • Space: O(1)
  • Stable: yes

Implementation notes

  • Kotlin: nested for loops with the early-exit swapped flag. arr.sort() would hide the comparison-and-swap the lesson is teaching.
  • The explicit val tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp three-line swap keeps the move visible without leaning on the (arr[j], arr[j+1]) = (arr[j+1], arr[j]) destructuring style.
  • The replay distinguishes compare frames from swap frames so the moving pivot value is visible. The pass number and swapped flag appear in the trace.
adjacent-pair compare and swap Inner loop walks `j` from `0` to `n - i - 2` comparing `arr[j]` and `arr[j + 1]`.
early exit A `swapped` flag set false at the start of each pass. If no swap happened, break out of the outer loop.