diff --git a/0215_kth_largest_element_in_an_array/kth_elem.c b/0215_kth_largest_element_in_an_array/kth_elem.c index bf9ea50..b14d278 100644 --- a/0215_kth_largest_element_in_an_array/kth_elem.c +++ b/0215_kth_largest_element_in_an_array/kth_elem.c @@ -2,6 +2,15 @@ #include +static void show(int *nums, int lo, int hi) +{ + int i; + for (i = lo; i <= hi; i++) { + printf("%d ", nums[i]); + } + printf("\n"); +} + static inline void swap(int *a, int *b) { int t = *a; @@ -38,41 +47,43 @@ static void build_max_heap(int *nums, int size) } } -static int quick_select(int *nums, int lo, int hi, int k) +static void quick_select(int *nums, int lo, int hi, int k) { if (lo >= hi) { - return hi; + return; } int i = lo - 1; - int j = hi + 1; - int pivot = nums[lo]; + int j = hi; + int pivot = nums[hi]; + while (i < j) { /* For case of large amounts of consecutive duplicate elements, we * shall make the partition in the middle of the array as far as * possible. If the partition is located in the head or tail, the * performance might well be very bad for it. */ - while (nums[++i] > pivot) {} - while (nums[--j] < pivot) {} + while (i < hi && nums[++i] > pivot) {} + while (j > lo && nums[--j] < pivot) {} if (i < j) { swap(&nums[i], &nums[j]); } } /* invariant: i == j + 1 or i == j */ - if (j >= k - 1) { - return quick_select(nums, lo, j, k); + swap(&nums[i], &nums[hi]); + if (i + 1 >= k) { + quick_select(nums, lo, i - 1, k); } else { - return quick_select(nums, j + 1, hi, k); + quick_select(nums, i + 1, hi, k); } } int findKthLargest(int* nums, int numsSize, int k) { -#if 0 - int i = quick_select(nums, 0, numsSize - 1, k); - return nums[i]; +#if 1 + quick_select(nums, 0, numsSize - 1, k); + return nums[k - 1]; #else int i;