-
Notifications
You must be signed in to change notification settings - Fork 108
/
QuickSort.kt
39 lines (34 loc) · 919 Bytes
/
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
fun main(args: Array<String>) {
val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
quickSort(array, 0, array.size-1)
for(i in array) println(i)
}
fun quickSort(array: IntArray, left: Int, right: Int) {
val index = partition (array, left, right)
if(left < index-1) {
quickSort(array, left, index-1)
}
if(index < right) {
quickSort(array,index, right)
}
}
fun partition(array: IntArray, l: Int, r: Int): Int {
var left = l
var right = r
val pivot = array[(left + right)/2]
while (left <= right) {
while (array[left] < pivot) left++
while (array[right] > pivot) right--
if (left <= right) {
swapArray(array, left,right)
left++
right--
}
}
return left
}
fun swapArray(a: IntArray, b: Int, c: Int) {
val temp = a[b]
a[b] = a[c]
a[c] = temp
}