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.

  • queerlilhayseed@piefed.blahaj.zoneOP
    link
    fedilink
    English
    arrow-up
    0
    ·
    13 days ago

    For the j > i case I think you’re right, it sorts largest to smallest (or, backwards), but for the j < i case it grabs larger values from [0, i] that it initially moved to the top of the array and slots them back in, effectively (if roundabout-ly) correcting the backwards sorting of the j > i part of the algorithm. Sort of a “two wrongs that accidentally make a right” maneuver.