The problem is from the cracking coding Interview programming book.
The problem is that:
Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array).
Below is my code in scala to sort Stack s, however, I think it is not the optimal solution in scala, may I know any other solutions can be written in functional programming language scala.
import scala.collection.mutable.Stack
def sorted(s: Stack[Int]): Unit={
def sortedwithtemp(original: Stack[Int], temp:Stack[Int], current: Int): Unit=(current, temp.top)match{
case (a,b) if a>=b =>temp.push(a);
if(original.size==0) original.pushAll(temp)
else {
val curr= original.pop()
sortedwithtemp(original, temp, curr)
}
case (a,b) => original.push(temp.pop());
if (temp.isEmpty) {temp.push(current); val curr= original.pop();sortedwithtemp(original, temp, curr)}
else sortedwithtemp(original, temp, current)
}
val tempstack=new Stack[Int]
if (s.size>=2){
tempstack.push(s.pop())
val current=s.pop()
sortedwithtemp(s, tempstack, current)
}
}