Sunday, June 21, 2015

sort stack using a stack and temp variable

sort(stack):
    sorted = new stack()
    while !stack.empty():
        temp = stack.pop()
        while !sorted.empty() && sorted.peek() > temp:
            stack.push(sorted.pop())
        sorted.push(temp)
    while !sorted.empty():
        stack.push(sorted.pop())

[Hat tip to ctci]

No comments:

Post a Comment