views:

610

answers:

7

Given a stack S, need to sort the stack using only Push, Pop, Top, IsEmpty, IsFull.

Looking for most simple solution.

Edited: Removed in place condition. Can't use another stack or queue.

+2  A: 

You can't. You can't reorder the contents of a stack without removing elements, by definition. Also push and pop aren't in-place operations, so basically you're asking to sort a stack with Top, IsEmpty and IsFull. IsEmpty = !IsFull. So you're asking to sort a stack with Top and IsEmpty.

Chris H
Err, your statement on IsEmpty and IsFull is wrong (for most stacks). If the stack is not empty, it's not necessarily full (unless it's a one-element stack). :)
Håvard S
Why aren't push and pop in-place operations?
sepp2k
well, to get access to the nth element you need to pop n-1 elements. the n depends on the input size so it's not constant size memory allocation therefore not in-place.
Chris H
I think it's possible to do it "in-place", for some definition. See my posted answer and my comment on George's answer.
DigitalRoss
+4  A: 

techInterview Discussion - Sorting on Stack

More pseudo than anything, but there is code examples and possible solution.

Anthony Forloney
I don't see how that is in-place. In-place means that you don't create any extra memory, save a few variables in O(1) space.
Chris H
OP had removed the in place condition
Anthony Forloney
People really need to take as wide an interpretation of the conditions as necessary in order to solve the problem. Obviously, in this case, in-place meant that another similarly-sized aggregate was not to be used, thus forcing a recursive solution with a temporary local variable or two in any given frame instance. Nothing is gained by taking a literal or overly pedantic view of the problem to the obviously-unintended extreme of permitting no solution.
DigitalRoss
If the question wanted a recursive answer, then IMO it makes more sense to say so, rather than imposing the very confusing condition "must implement this in a way which, in an imperative language, is pretty much guaranteed to be worse in every single way than using a second data structure". Of course this is a complaint about interview puzzlers in general rather than this question in particular :-)
Steve Jessop
+2  A: 

Its not possible.

That happens because you cant iterate through the stack, because it has to be in place (you could if you would use extra memory). So if you cant iterate through the stack you cant even compare two elements of the stack. A sort without comparing would need extra memory, so that cant be used either.

Also im sure its not homework, because i dont think a teacher would give you a problem that cant be solved.

If you really have to do it only with stacks, just use 1-2 extra temporary stacks (i think 2 are needed, but not 100% sure) and do it.

George B.
Except, I just did it. Presumably a recursive solution was the intended solution, even though this certainly requires some sort of behind-the-scenes data structure. I think it's best to handle this kind of problem by coming up with some sort of solution that in some way meets the criteria. I doubt if the prof will be too impressed by "it's impossible".
DigitalRoss
As you said, you are using a "behind-the-scenes" data structure, which is the call stack. I should maybe better say its not possible with iteration, but possible with recursion :) . Edit: also my answer when he wanted an in-place solution (now he changed the topic), which is not one with recursion, because to be in-place the space used has to be a constant (which it isnt because you are using as much stack space you want).
George B.
+5  A: 

It can be done...


Ok: sorted, ahem, "in-place" with only the listed ops, didn't need Top() or IsFull() or another stack or data structure other than the call frames. (Presumably the whole point of the homework problem was to require a recursive solution.)

Ruby

@a = [3, 2, 1, 6, 5, 4]

class Array
  def empty?
    return size == 0
  end
end

def sort e
  if @a.empty?
    @a.push e
    return
  end
  t = @a.pop
  if e > t
    @a.push(t).push(e)
    return
  end
  sort e
  @a.push t
end

def resort
  return if @a.empty?
  t = @a.pop
  resort
  sort t
end

p ['first ', @a]
resort
p ['final ', @a]
DigitalRoss
So this one works by defining two sort functions: `resort` which does not assume that the stack is already sorted and `sort` which does. Both work by recursively popping an element off until their goal is reached. In the case of the top-level `resort`, it's goal is to remove everything and build it back up by calling `sort`, and `sort` works by recursing just far enough to push a single element. I have to think a solution like this was the point of the exercise.
DigitalRoss
You are using extra memory; surely not explicitly organized as a stack (rather hidden in the call stack) but I'm curious if the OP's satisfied.
Michael Foukarakis
Sure, but I think that was intended. Maybe this solution would be obvious to some people, but I had to think a bit to get this. It's a fun problem and I suspect it was designed to require pretty much this solution.
DigitalRoss
+2  A: 

What temporary data structures can you use? With push and pop, and no temporary storage for n elements, accessing data near the bottom of the stack would be impossible without storing the rest -somewhere-.

If top (equiv to {x=pop();push(x);return x}) was replaced with shift, it would be perfectly doable - the stack would change into fifo (shift+push; pop would fall into disuse) and it would allow for an easy bubblesort on currently available elements.

SF.
A: 

For this problem, can we consider using system stack? Make several recursive calls.

public static void sort(Stack<Integer> s) {
    if (!s.isEmpty()) {
        Integer t = s.pop();
        sort(s);
        insert(t, s);
    }
}

private static void insert(Integer x, Stack<Integer> s) {
    if (s.isEmpty()) {
        s.push(x);
        return;
    }

    if (x < s.peek()) {
        Integer t = s.pop();
        insert(x, s);
        s.push(t);
    } else {
        s.push(x);
    }
}
SiLent SoNG
+1  A: 

To bad you couldn't have two other stacks, then you could have played the Towers of Hanoi in O(n) space.

Albin Sunnanbo