Sorting
Bubble Sort
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.lua
local arr = {5, 1, 4, 2, 8}
local n = #arr
local i = 1
local done = false
while i <= n - 1 and not done do
local swapped = false
local j = 1
while j <= n - i do
if arr[j] > arr[j + 1] then
local tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
swapped = true
end
j = j + 1
end
if not swapped then
done = true
end
i = i + 1
end
io.write("[")
for k = 1, #arr do
if k > 1 then io.write(", ") end
io.write(tostring(arr[k]))
end
io.write("]\n")
Complexity
- Time: O(n^2) worst and average; O(n) best (already sorted with early exit)
- Space: O(1)
- Stable: yes
Implementation notes
- Lua: explicit
whileloops withi,j,done, andswappedso the early-exit flow stays visible. The stdlibtable.sort(arr)would hide the comparison-and-swap the lesson is teaching, and agoto continueinside aforloop would collapse thedoneflag into a control-flow shortcut. - The explicit
local tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmpthree-line swap keeps the move visible without leaning on Lua's parallel assignmentarr[j], arr[j+1] = arr[j+1], arr[j]. - The replay distinguishes compare frames from swap frames so the
moving pivot value is visible. The pass number and
swappedflag appear in the trace.
adjacent-pair compare and swap
Inner loop walks `j` from `1` to `n - i` comparing `arr[j]` and `arr[j + 1]`.
early exit
A `swapped` flag set `false` at the start of each pass. If no swap happened, flip a `done` flag and break out of the outer loop.