- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path215.c
85 lines (62 loc) · 1.98 KB
/
215.c
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<stdio.h>
intfindKthLargest(int*nums, intnumsSize, intk) {
if (k<1||k>numsSize) return0;
intpivot=nums[0];
inti=0, j=numsSize-1;
while (i<j) {
while (i<j&&nums[j] >= pivot)
j--;
nums[i] =nums[j];
while (i<j&&nums[i] <= pivot)
i++;
nums[j] =nums[i];
}
nums[i] =pivot;
intrightSize=numsSize-i-1; /* size of right sub array */
if (rightSize+1==k) { /* found, it's pivot */
returnnums[i];
}
if (rightSize >= k) {
returnfindKthLargest(nums+i+1, rightSize, k); /* find in right half */
}
else {
returnfindKthLargest(nums, i, k-rightSize-1); /* find in left half */
}
}
voidswap(int*a, int*b) {
intt=*a;
*a=*b;
*b=t;
}
/* another method, diff from Hoare's quicksort */
intfindKthLargest0(int*nums, intnumsSize, intk) {
if (k<1||k>numsSize) return0;
intpivotIndex=0; /* select a pivot, simply use leftest elem */
intpivotValue=nums[pivotIndex];
inti=0; /* store index */
intj; /* sweep index */
swap(&nums[pivotIndex], &nums[numsSize-1]);
for (j=0; j<numsSize-1; j++) {
if (nums[j] <= pivotValue) {
swap(&nums[j], &nums[i]);
i++;
}
}
swap(&nums[i], &nums[numsSize-1]);
intrightSize=numsSize-i-1; /* size of right sub array */
if (rightSize+1==k) { /* found, it's pivot */
returnnums[i];
}
if (rightSize >= k) {
returnfindKthLargest0(nums+i+1, rightSize, k); /* find in right half */
}
else {
returnfindKthLargest0(nums, i, k-rightSize-1); /* find in left half */
}
}
intmain() {
intn[] = { 3, 7, 8, 1, 2, 5, 6, 9 };
/* should be 7 */
printf("%d\n", findKthLargest(n, sizeof(n) / sizeof(n[0]), 3));
return0;
}