|
2 | 2 | #include <stdlib.h> |
3 | 3 |
|
4 | 4 |
|
| 5 | +static void show(int *nums, int lo, int hi) |
| 6 | +{ |
| 7 | + int i; |
| 8 | + for (i = lo; i <= hi; i++) { |
| 9 | + printf("%d ", nums[i]); |
| 10 | + } |
| 11 | + printf("\n"); |
| 12 | +} |
| 13 | + |
5 | 14 | static inline void swap(int *a, int *b) |
6 | 15 | { |
7 | 16 | int t = *a; |
@@ -38,41 +47,43 @@ static void build_max_heap(int *nums, int size) |
38 | 47 | } |
39 | 48 | } |
40 | 49 |
|
41 | | -static int quick_select(int *nums, int lo, int hi, int k) |
| 50 | +static void quick_select(int *nums, int lo, int hi, int k) |
42 | 51 | { |
43 | 52 | if (lo >= hi) { |
44 | | - return hi; |
| 53 | + return; |
45 | 54 | } |
46 | 55 |
|
47 | 56 | int i = lo - 1; |
48 | | - int j = hi + 1; |
49 | | - int pivot = nums[lo]; |
| 57 | + int j = hi; |
| 58 | + int pivot = nums[hi]; |
| 59 | + |
50 | 60 | while (i < j) { |
51 | 61 | /* For case of large amounts of consecutive duplicate elements, we |
52 | 62 | * shall make the partition in the middle of the array as far as |
53 | 63 | * possible. If the partition is located in the head or tail, the |
54 | 64 | * performance might well be very bad for it. |
55 | 65 | */ |
56 | | - while (nums[++i] > pivot) {} |
57 | | - while (nums[--j] < pivot) {} |
| 66 | + while (i < hi && nums[++i] > pivot) {} |
| 67 | + while (j > lo && nums[--j] < pivot) {} |
58 | 68 | if (i < j) { |
59 | 69 | swap(&nums[i], &nums[j]); |
60 | 70 | } |
61 | 71 | } |
62 | 72 |
|
63 | 73 | /* invariant: i == j + 1 or i == j */ |
64 | | - if (j >= k - 1) { |
65 | | - return quick_select(nums, lo, j, k); |
| 74 | + swap(&nums[i], &nums[hi]); |
| 75 | + if (i + 1 >= k) { |
| 76 | + quick_select(nums, lo, i - 1, k); |
66 | 77 | } else { |
67 | | - return quick_select(nums, j + 1, hi, k); |
| 78 | + quick_select(nums, i + 1, hi, k); |
68 | 79 | } |
69 | 80 | } |
70 | 81 |
|
71 | 82 | int findKthLargest(int* nums, int numsSize, int k) |
72 | 83 | { |
73 | | -#if 0 |
74 | | - int i = quick_select(nums, 0, numsSize - 1, k); |
75 | | - return nums[i]; |
| 84 | +#if 1 |
| 85 | + quick_select(nums, 0, numsSize - 1, k); |
| 86 | + return nums[k - 1]; |
76 | 87 | #else |
77 | 88 | int i; |
78 | 89 |
|
|
0 commit comments