The following is a text-book quick sort implementation in Scala. When comparing the execution time of quickSortRecursive to java.util.Arrays.sort(), I found java.util.Arrays.sort to be an order of magnitude faster on large arrays. Can someone hint on the reason for this difference in performance?
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
}