Reputation: 35
I had to find what that mystery algorithm does. Now I know it's a sort, but I can't find an official name for it.
Here is its Java code:
for (int i = 0 ; i < myListSize; i++) {
min = Collections.min(myList.subList(i, myListSize));
minIndex = myList.indexOf(min);
Collections.reverse(myList.subList(minIndex, myListSize));
Collections.reverse(myList.subList(i, myListSize));
}
Take this array:
[G,E,D,A,F,C,H,I,B]
It 1) searches for the min. element, 2) reverses the subarray from there and 3) reverses the whole thing again:
1) [G,E,D,[A,F,C,H,I,B]]
2) [G,E,D,[B,I,H,C,F,A]]
3) [[A,F,C,H,I,B],D,E,G]
Now the min. element is on the left. Repeat for the remainder of the array:
1) [A] [F,C,H,I,[B,D,E,G]]
2) [A] [F,C,H,I,[G,E,D,B]]
3) [A] [[B,D,E,G],I,H,C,F]
1) [A,B] [D,E,G,I,H,[C,F]]
2) ...
and voilà! Sorted. Do you have a name for it, please ?
Upvotes: 1
Views: 169
Reputation: 29949
It's called Pancake sorting.
Here's a code golf puzzle about it: Flipping pancakes
Upvotes: 8