Sorting Bubbles Before They Burst
A soap bubble can offer a whole portfolio in a few seconds: a bright swirl, a darkening crown, then an empty frame. Imagine scoring each photograph for sharpness and putting the best candidates first. If two frames receive the same score, their original order may still matter: it preserves the sequence in which the colours appeared.
A stable sort keeps equal keys in their original relative order. Merge sort, developed in the 1940s and widely used by the 1960s, can do this by choosing the left-hand item first when two keys compare equal. Here, Go’s stable sorting function handles that detail for us:
package main
import (
"fmt"
"sort"
)
func main() {
frames := []struct{ name string; score int }{
{"swirl", 8}, {"crown", 9}, {"rim", 8},
}
sort.SliceStable(frames, func(i, j int) bool {
return frames[i].score > frames[j].score
})
fmt.Println(frames)
}
The result places crown first, followed by swirl and rim. Those last two have equal scores, so their capture order survives.
Lua’s table.sort does not promise stability. We can give it a tiebreaker instead: attach each frame’s original position, then compare positions when scores match.
local frames = {
{name = "swirl", score = 8},
{name = "crown", score = 9},
{name = "rim", score = 8},
}
for i, frame in ipairs(frames) do frame.position = i end
table.sort(frames, function(a, b)
if a.score ~= b.score then return a.score > b.score end
return a.position < b.position
end)
for _, frame in ipairs(frames) do print(frame.name, frame.score) end
The Lua version produces the same ordering, though its extra position field takes a little space and changes each frame’s data. Stability is useful whenever equal-ranked records carry a meaningful earlier order; it does not, however, tell us whether the sharpness score was a good measure of the photograph. That part still needs an eye for bubbles.