Gnome Sort
July 29, 2016
A garden gnome sorts flower pots by the following method:
The gnome looks at the flower pot next to him and the flower pot just behind him. If they are correctly ordered, so the flower pot just behind him is smaller than the flower pot next to him, he steps one pot forward; otherwise, he swaps the two flower pots and steps one pot backward. If there is no flower pot just behind him (thus, he is at the start of the line of flower pots), he steps forward to the next pot. If there is not flower pot next to him (thus, he is at the end of the line of flower pots), he is done.
Your task is to implement a program that sorts by the gnome method. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
As a bit of perl golf!
but this gnome is not instructed to go start at the start of the row, and there seem to be some unattended pots left behind fairly often.
(How would ties behave? I meant to accept them as ordered but I see now that I forgot. Uh oh. :)
@Jussi: In my solution, ties cause an infinite loop. Oops!
@Praxis, I suspect mine does the same.
Here’s a solution in C.
Output:
Heh, checked the reference solution after getting mine done. They look preeetty similar.
Isn’t this just a variant of insertion sort?
> “Isn’t this just a variant of insertion sort?”
If the gnome could jump over all the flower pots he swapped with when swapping a pot into place, it would seemingly be insertion sort.
@Daniel: indeed, the sequence of swaps are the same as for a (swap-based) insertion sort, but more comparisons are made as we don’t keep track of the position of the last out of order item.
Gnomesort is nicely represented as a Markov program (see https://matthewarcus.wordpress.com/2014/01/08/markov-computation/ for explanation & a little interpreter). Here we have some rewrite rules for sorting sequences of two different items A and B, * is the gnome, who stands in-between the flower pots:
Since I didn’t see a Python Solution: