Lines 44
##### Keywords
algorithm (8) quicksort (5) sort (5)
##### Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Stay up to dateembedded code automagically updates, each snippet and article has a feed

# Imperative implementation of QuickSort 0

 In Brief A Scala implementation of Quick Sort using imperative programming (i.e. what you are used to). Compare this implementation to the much shorter functional version
 Language Scala
# 's
` 1/** Quick sort, imperative style */ 2object ImperativeQuickSort { 3 4  /** Nested methods can use and even update everything  5   *  visible in their scope (including local variables or  6   *  arguments of enclosing methods).  7   */ 8  def sort(a: Array[Int]) { 910    def swap(i: Int, j: Int) {11      val t = a(i); a(i) = a(j); a(j) = t12    }1314    def sort1(l: Int, r: Int) {15      val pivot = a((l + r) / 2)16      var i = l17      var j = r18      while (i <= j) {19        while (a(i) < pivot) i += 120        while (a(j) > pivot) j -= 121        if (i <= j) {22          swap(i, j)23          i += 124          j -= 125        }26      }27      if (l < j) sort1(l, j)28      if (j < r) sort1(i, r)29    }3031    if (a.length > 0)32      sort1(0, a.length - 1)33  }3435  def println(ar: Array[Int]) {36    def print1 = {37      def iter(i: Int): String =38        ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")39      if (ar.length == 0) "" else iter(0)40    }41    Console.println("[" + print1 + "]")42  }4344  def main(args: Array[String]) {45    val ar = Array(6, 2, 8, 5, 1)46    println(ar)47    sort(ar)48    println(ar)49  }5051}`

A Scala implementation of Quick Sort using imperative programming (i.e. what you are used to). Compare this implementation to the much shorter functional version