I learned about this from Matt Parker's Stand-Up Maths channel. It was originally conceived as a counterexample, a sorting algorithm that was obviously broken, but it does actually sort correctly. The algorithm:

for i = 1 to n do  
	for j = 1 to n do  
		if A[i] < A[j] then  
			swap A[i] and A[j]  

It has a few quirks (like j accessing elements outside of i's range, and the A[i] < A[j] comparator being backward) that should break it, but they all work together to make the algorithm correctly (if inefficiently) sort the input.

paper describing the algorithm in more detail.

you are viewing a single comment's thread
view the rest of the comments
[–] 12 points 2 months ago (1 child)

It really does look more broken the more I look. I began to think that it would sort odd and even lists in opposite orders, since half the time it's comparing pairs the opposite way around.

  • source
  • parent
  • hideshow 1 child comment
  • [–] 3 points 2 months ago* (last edited 2 months ago)

    it would sort odd and even lists in opposite orders

    not sure why you see different behaviour based on parity, but it does sort in descending order. that is why the inequality operator in if A[i] < A[j] then swap is reversed.

  • source
  • parent