Last active
November 1, 2016 16:25
-
-
Save kseada/1de78535c12d96452113 to your computer and use it in GitHub Desktop.
Quick Sort in Scala.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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