Skip to content

Commit 0d16d6e

Browse files
Improvement
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 545e87d commit 0d16d6e

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

0215_kth_largest_element_in_an_array/kth_elem.c

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@
22
#include <stdlib.h>
33

44

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+
514
static inline void swap(int *a, int *b)
615
{
716
int t = *a;
@@ -38,41 +47,43 @@ static void build_max_heap(int *nums, int size)
3847
}
3948
}
4049

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)
4251
{
4352
if (lo >= hi) {
44-
return hi;
53+
return;
4554
}
4655

4756
int i = lo - 1;
48-
int j = hi + 1;
49-
int pivot = nums[lo];
57+
int j = hi;
58+
int pivot = nums[hi];
59+
5060
while (i < j) {
5161
/* For case of large amounts of consecutive duplicate elements, we
5262
* shall make the partition in the middle of the array as far as
5363
* possible. If the partition is located in the head or tail, the
5464
* performance might well be very bad for it.
5565
*/
56-
while (nums[++i] > pivot) {}
57-
while (nums[--j] < pivot) {}
66+
while (i < hi && nums[++i] > pivot) {}
67+
while (j > lo && nums[--j] < pivot) {}
5868
if (i < j) {
5969
swap(&nums[i], &nums[j]);
6070
}
6171
}
6272

6373
/* 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);
6677
} else {
67-
return quick_select(nums, j + 1, hi, k);
78+
quick_select(nums, i + 1, hi, k);
6879
}
6980
}
7081

7182
int findKthLargest(int* nums, int numsSize, int k)
7283
{
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];
7687
#else
7788
int i;
7889

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy