|
5 | 5 | ### 快速排序 |
6 | 6 |
|
7 | 7 | ```c |
8 | | -func QuickSort(nums []int) []int { |
| 8 | +void QuickSort(vector<int>& nums, int n){ |
9 | 9 | // 思路:把一个数组分为左右两段,左段小于右段 |
10 | | - quickSort(nums, 0, len(nums)-1) |
11 | | - return nums |
12 | | - |
| 10 | + quickSort(nums, 0, n - 1); |
13 | 11 | } |
| 12 | + |
14 | 13 | // 原地交换,所以传入交换索引 |
15 | | -func quickSort(nums []int, start, end int) { |
16 | | - if start < end { |
| 14 | +void quickSort(vector<int>& nums, int start, int end) { |
| 15 | + if (start < end) { |
17 | 16 | // 分治法:divide |
18 | | - pivot := partition(nums, start, end) |
19 | | - quickSort(nums, 0, pivot-1) |
20 | | - quickSort(nums, pivot+1, end) |
| 17 | + int pivot = partition(nums, start, end); |
| 18 | + quickSort(nums, 0, pivot-1); |
| 19 | + quickSort(nums, pivot+1, end); |
21 | 20 | } |
22 | 21 | } |
23 | 22 | // 分区 |
24 | | -func partition(nums []int, start, end int) int { |
| 23 | +int partition(vector<int>& nums, int start, int end){ |
25 | 24 | // 选取最后一个元素作为基准pivot |
26 | | - p := nums[end] |
27 | | - i := start |
| 25 | + int p = nums[end]; |
| 26 | + int i = start; |
28 | 27 | // 最后一个值就是基准所以不用比较 |
29 | | - for j := start; j < end; j++ { |
30 | | - if nums[j] < p { |
31 | | - swap(nums, i, j) |
32 | | - i++ |
| 28 | + for (int j = start; j < end; j++) { |
| 29 | + if (nums[j] < p) { |
| 30 | + swap(nums[i], nums[j]); |
| 31 | + i++; |
33 | 32 | } |
34 | 33 | } |
35 | 34 | // 把基准值换到中间 |
36 | | - swap(nums, i, end) |
37 | | - return i |
38 | | -} |
39 | | -// 交换两个元素 |
40 | | -func swap(nums []int, i, j int) { |
41 | | - t := nums[i] |
42 | | - nums[i] = nums[j] |
43 | | - nums[j] = t |
| 35 | + swap(nums[i], nums[end]); |
| 36 | + return i; |
44 | 37 | } |
45 | 38 | ``` |
46 | 39 |
|
|
0 commit comments