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
| class Solution {
func sortArray(_ nums: [Int]) -> [Int] {
let left = 0, right = nums.count - 1
var arr = nums
quickSort(&arr, left, right)
return arr
}
func quickSort(_ nums: inout [Int], _ low: Int, _ high: Int) {
guard low < high else {
return
}
let randomIndex = Int.random(in: (low...high))
let pivot = nums[randomIndex]
// 把随机选择的数放到最前面
nums.swapAt(low, randomIndex)
var left = low, right = high
while left < right {
while left < right, pivot <= nums[right] {
right -= 1
}
while left < right, nums[left] <= pivot {
left += 1
}
if left < right {
nums.swapAt(left, right)
}
}
// 把pivot交换回来
nums.swapAt(left, low)
quickSort(&nums, low, left - 1)
quickSort(&nums, left + 1, high)
}
}
|