I was inspired to post this by a question about sorting algorithms over in GQ, but since this isn’t so serious I’m posting over here in MP to start.
This is a question I first thought about in university, playing around with a deck of cards and thinking about the sorting stuff I was learning in my programming classes. Basically, it’s attempting to sort in a very minimalist environment.
The three-stack sorting puzzle
You start with a huge number of elements on one stack, in an unspecified order. You may do any of the following things:
- Move elements from one stack to another, out of three available: A, B, and C. (As a convention, elements start on stack A)
- Test to see if a stack is empty
- If two stacks are both non-empty, then test to see if one is less than or greater than the other.
- Set or unset a single memory flag
- Test the status of the flag.
And of course, you can use control structures, loops and case statements, as you please. (Even subroutines or functions, except you can’t use them to create any other data space than the three stacks and the flag.)
The objective: to design an efficient algorithm under these conditions to sort the elements in ascending order on a single stack. (If elements are equal, then their order is unimportant.) You can sort to any stack you please.
I’ll provide the code for a bubble sort as an example. Selection sort and insertion sort are also fairly easy to implement in three-stack, (at least I found it so,) but the traditional recursive algorithms for mergesort or quicksort are completely infeasible. I’ve found one solution for O(n log n) time - maybe dopers can work out another!
Three-stack bubble sort
(Unsorted elements start on stack A)
DO
unset flag
DO
moveFrom A to B
If isEmpty(A) then EXIT DO
If top(A) < top(B) then
moveFrom B to C
moveFrom A to B
moveFrom C to A
set flag
end-if
LOOP
DO while not isEmpty(B)
moveFrom B to A
LOOP
if flag is unset then EXIT DO
LOOP
return A
If you have questions, please ask away.