-
Notifications
You must be signed in to change notification settings - Fork 108
/
QuickSort.kt
53 lines (45 loc) · 1.16 KB
/
QuickSort.kt
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package sorting
import kotlin.random.Random
/**
*
* QuickSort is a sorting algorithm based on the Divide and Conquer algorithm
*
* that picks an element as a pivot and partitions the given array around the picked pivot
*
* by placing the pivot in its correct position in the sorted array.
*
*
* worst time: n²
* best time: n * log(n)
* average time: n * log(n)
*
* amount of memory: n
*
*/
class QuickSort {
fun <T : Comparable<T>> sort(array: Array<T>, start: Int = 0, end: Int = array.size - 1) {
if (array.isEmpty()) return
if (start >= end) return
val pivotIndex = Random.nextInt(start, end + 1)
val pivot = array[pivotIndex]
var i = start
var j = end
while (i <= j) {
while (array[i] < pivot) {
i++
}
while (array[j] > pivot) {
j--
}
if (i <= j) {
val tmp = array[i]
array[i] = array[j]
array[j] = tmp
i++
j--
}
}
if (i < end) sort(array, i, end)
if (0 < j) sort(array, start, j)
}
}