Skip to content

Commit 5faff6b

Browse files
committed
Fixes #20 Idomatic way of implementing quicksort
1 parent 0f7bd4a commit 5faff6b

File tree

1 file changed

+3
-25
lines changed

1 file changed

+3
-25
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
package divideandconquer
22

3-
import scala.annotation.tailrec
4-
import util.Utility.swap
5-
63
/*
74
An implementation of the quick sort algorithm
85
*/
@@ -17,28 +14,9 @@ object QuickSort extends App{
1714
case Array() | Array(_) => arr
1815
case _ =>
1916
val pivotPos = arr.length/2
20-
val (newArray, finalPivotPos) = movePivotToCorrectPos(arr, pivotPos)
21-
quickSort(newArray.take(finalPivotPos)) ++ Array(newArray(finalPivotPos)) ++ quickSort(newArray.drop(finalPivotPos + 1))
22-
}
23-
24-
def movePivotToCorrectPos(array: Array[Int], pivotPos: Int): (Array[Int], Int) = {
25-
val pivot = array(pivotPos)
26-
val lowIndex = 1
27-
val highIndex = array.length - 1
28-
29-
@tailrec
30-
def recur(arr: Array[Int], lI: Int, hI: Int): (Array[Int], Int) =
31-
if(lI > hI) (arr, hI)
32-
else if (arr(lI) > pivot) {
33-
val newArray = swap(arr, lI, hI)
34-
recur(newArray, lI, hI - 1)
35-
} else {
36-
recur(arr, lI + 1, hI)
37-
}
17+
val pivot = arr(pivotPos)
3818

39-
val mTemp = swap(array, 0, pivotPos) //move pivot to 0 index
40-
val (newArray, correctPivotPos) = recur(mTemp, lowIndex, highIndex)
41-
val finalArray = swap(newArray, 0, correctPivotPos) //move pivot to correct pos
42-
(finalArray, correctPivotPos)
19+
val withoutPivot = arr diff Array(pivot)
20+
quickSort(withoutPivot.filter(_ < pivot)) ++ Array(pivot) ++ quickSort(withoutPivot.filterNot(_ < pivot))
4321
}
4422
}

0 commit comments

Comments
 (0)