Yes we can. The trick is to understand that when sorting a stack, the head is the largest element - and we want to iterate over it from lower to higher. We can flip the stack, but in O (n).
reverse(stack):
s <- new stack
while stack.isEmpty() == false:
s.push(stack.pop)
return s
, , size(), - :
:
mergeSort(stack):
if stack.isEmpty():
return stack
s1 <- new stack
s2 <- new stack
while s1.size() < stack.size():
s1.push(stack.pop())
while (stack.isEmpty() == false):
s2.push(stack.pop())
mergeSort(s1)
mergeSort(s2)
s1 <- s1.reverse()
s2 <- s2.reverse()
while (s1.isEmpty() == false and s2.isEmpty() == false):
if (s1.peek() < s2.peek()):
stack.push(s1.pop())
else:
stack.push(s2.pop())
while (s1.isEmpty() == false):
stack.push(s1.pop())
while (s2.isEmpty() == false):
stack.push(s2.pop())
return stack
:
: stop - , .
: s1 s2 .
: s1 s2 → , pop(). , - , .
:
, O(stack.size()) = O(n). , , , O(nlogn).