-
Notifications
You must be signed in to change notification settings - Fork 2
/
QuickSort.scala
36 lines (34 loc) · 1.19 KB
/
QuickSort.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package sortingAlgorithms
/**
* This object contains function, that realises quick sorting algorithm.
*
* https://en.wikipedia.org/wiki/Quicksort
*
* Worst speed: O(pow(n))
*
* Average speed: O(n*log(n))
*
* Best speed: O(n*log(n))
*
* In case that we take first element as pivot, algorithm works worse with sorted lists.
*
* Purity project by Daniil Tekunov.
*/
object QuickSort {
def quickSort(list: List[Int]): List[Int] = {
list match {
// If a list contains no elements, we do not return anything.
case Nil => Nil
// If a list contains only one element, we just return it.
case singleElement :: Nil => List(singleElement)
// If a list contains more than one element,
case middleElem :: tail =>
// we quickSort the part of the list, that is less than middle element,
quickSort(tail.filter(lessElem => lessElem <= middleElem)) :::
// we add middle element to a sorted part above.
List(middleElem) :::
// and we quickSort the part of the list, that is greater than middle element and add it to a list above.
quickSort(tail.filter(greaterElem => greaterElem > middleElem))
}
}
}