Sort Using Two Stacks

Write a program to sort a stack using additional stacks but no other data structures

import scala.collection.mutable.Stack

/**
  * 3.6
  * @param s1
  * @return
  */
def sort(s1:Stack[Int]): Stack[Int] = {
  val s2 = Stack[Int]()
  while (!s1.isEmpty) {
    val tmp = s1.pop()
    while (!s2.isEmpty && s2.head < tmp) {
      s1.push(s2.pop())
    }
    s2.push(tmp)
  }
  s2
}

val s = Stack[Int]()
s.push(3)
s.push(9)
s.push(5)

val s3 = sort(s)
while (!s3.isEmpty) {
  println(s3.pop())
}

Last updated