calgorithmdata-structures

How to sort a stack using only Push, Pop, Top, IsEmpty, IsFull?


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.


Solution

  • 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]