forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick_Sort.kt
63 lines (53 loc) · 1.23 KB
/
Quick_Sort.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
54
55
56
57
58
59
60
61
62
/* QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array
around the picked pivot.It's Best case complexity is n*log(n) & Worst case complexity is n^2. */
//partition array
fun quick_sort(A: Array<Int>, p: Int, r: Int) {
if (p < r) {
var q: Int = partition(A, p, r)
quick_sort(A, p, q - 1)
quick_sort(A, q + 1, r)
}
}
//assign last value as pivot
fun partition(A: Array<Int>, p: Int, r: Int): Int {
var x = A[r]
var i = p - 1
for (j in p until r) {
if (A[j] <= x) {
i++
exchange(A, i, j)
}
}
exchange(A, i + 1, r)
return i + 1
}
//swap
fun exchange(A: Array<Int>, i: Int, j: Int) {
var temp = A[i]
A[i] = A[j]
A[j] = temp
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
quick_sort(A, 0, A.size - 1)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
/*-------OUTPUT--------------
Enter no. of elements :6
Enter elements :
4
8
5
9
2
6
Sorted array is :
2 4 5 6 8 9
*/