Image Video of Pancake Sort
Source code of scala
object PancakeSort {
def main(args: Array[String]) {
// Prepare input values
val arr = List(23, 10, 20, 11, 12, 6, 7)
// Do pancake sort
val result = pancakeSort((for(x <- 0 to arr.size-1) yield (x, arr(x))).toList, arr.size)
// Output the result
println("Input")
arr.foreach(x => println(x))
println("Output:")
result.foreach(x => println(x._2))
}
def pancakeSort(arr: List[(Int, Int)], n:Int):List[(Int, Int)] = {
// Apply flip operator from idx 0th to nth
if (n <= 0) return arr else return pancakeSort(flips(arr.filter(x => x._1 <= n)) ::: arr.filter(x => x._1 > n), n-1)
}
def flips(arr: List[(Int, Int)]):List[(Int, Int)] = {
// Get index of max value
val max_index = arr.reduceLeft{ (a,b) => if (a._2 > b._2) (a._1, a._2) else (b._1, b._2) }._1
// Place max value to tail
val tmp_arr = (arr.filter(a => a._1 <= max_index).reverse ::: arr.filter(a => a._1 > max_index)).reverse
// Refine value's index
return (for (x <- 0 to tmp_arr.size-1) yield (x, tmp_arr(x)._2)).toList
}
}