forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0912-sort-an-array.kt
135 lines (111 loc) · 2.97 KB
/
0912-sort-an-array.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
* Merge sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
mergeSort(nums, 0, nums.lastIndex)
return nums
}
private fun mergeSort(nums: IntArray, left: Int, right: Int) {
if(left == right) return
val mid = (left + right) / 2
mergeSort(nums, left, mid)
mergeSort(nums, mid + 1, right)
merge(nums, left, mid, right)
return
}
private fun merge(nums: IntArray, left: Int, mid: Int, right: Int) {
val leftPart = nums.copyOfRange(left, mid + 1)
val rightPart = nums.copyOfRange(mid + 1, right + 1)
var i = left
var j = 0
var k = 0
while(j < leftPart.size && k < rightPart.size) {
if(leftPart[j] <= rightPart[k]) {
nums[i] = leftPart[j]
j++
}else{
nums[i] = rightPart[k]
k++
}
i++
}
while(j < leftPart.size) {
nums[i] = leftPart[j]
j++
i++
}
while(k < rightPart.size) {
nums[i] = rightPart[k]
k++
i++
}
}
}
/*
* Quick sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
quickSort(nums, 0, nums.lastIndex)
return nums
}
private fun quickSort(nums: IntArray, low: Int, high: Int) {
if (low < high) {
val pivotIndex = partition(nums, low, high)
quickSort(nums, low, pivotIndex - 1)
quickSort(nums, pivotIndex + 1, high)
}
}
private fun partition(nums: IntArray, low: Int, high: Int): Int {
val r = (low..high).random()
nums.swap(r, high)
val pivot = nums[high]
var i = low
for (j in low until high) {
if (nums[j] <= pivot) {
nums.swap(i, j)
i++
}
}
nums.swap(i, high)
return i
}
fun IntArray.swap(i: Int, j: Int) {
this[i] = this[j].also { this[j] = this[i] }
}
}
/*
* Heap sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
heapSort(nums)
return nums
}
private fun heapSort(nums: IntArray) {
val n = nums.size
for(i in (n/2 - 1) downTo 0)
heapify(nums, n, i)
for(i in n-1 downTo 0) {
nums.swap(0, i)
heapify(nums, i, 0)
}
}
private fun heapify(nums: IntArray, n: Int, i: Int) {
var largest = i
val left = 2 * i + 1
val right = 2 * i + 2
if(left < n && nums[left] > nums[largest])
largest = left
if(right < n && nums[right] > nums[largest])
largest = right
if(largest != i) {
nums.swap(i, largest)
heapify(nums, n, largest)
}
}
fun IntArray.swap(i: Int, j: Int) {
this[i] = this[j].also{ this[j] = this[i] }
}
}