Skip to content

Instantly share code, notes, and snippets.

@kseada
Last active November 1, 2016 16:25
Show Gist options
  • Save kseada/1de78535c12d96452113 to your computer and use it in GitHub Desktop.
Save kseada/1de78535c12d96452113 to your computer and use it in GitHub Desktop.
Quick Sort in Scala.
def quickSortRecursive(list: Array[Int])(low: Int=0, high: Int=list.length-1): Unit = {
if (low<high) {
swap(list,Random.nextInt(high),high)
val pivot = partition(list, low, high)
quickSortRecursive(list)(low, pivot-1)
quickSortRecursive(list)(pivot+1, high)
}
}
private def partition(list: Array[Int], low: Int, high: Int): Int = {
val pivot = list(high)
var lowhigh = low
for (i <- low until high) {
if (list(i) < pivot) {
swap(list, lowhigh, i);
lowhigh += 1;
}
}
swap(list, lowhigh, high);
lowhigh
}
private def swap(list: Array[Int], i: Int, j: Int): Unit = {
val tmp = list(i)
list(i) = list(j)
list(j) = tmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment