@@ -34,6 +34,46 @@ int findKthLargest(int* nums, int numsSize, int k) {
34
34
}
35
35
}
36
36
37
+ void swap (int * a , int * b ) {
38
+ int t = * a ;
39
+ * a = * b ;
40
+ * b = t ;
41
+ }
42
+
43
+ /* another method, diff from Hoare's quicksort */
44
+ int findKthLargest0 (int * nums , int numsSize , int k ) {
45
+ if (k < 1 || k > numsSize ) return 0 ;
46
+
47
+ int pivotIndex = 0 ; /* select a pivot, simply use leftest elem */
48
+ int pivotValue = nums [pivotIndex ];
49
+ int i = 0 ; /* store index */
50
+ int j ; /* sweep index */
51
+
52
+ swap (& nums [pivotIndex ], & nums [numsSize - 1 ]);
53
+
54
+ for (j = 0 ; j < numsSize - 1 ; j ++ ) {
55
+ if (nums [j ] <= pivotValue ) {
56
+ swap (& nums [j ], & nums [i ]);
57
+ i ++ ;
58
+ }
59
+ }
60
+
61
+ swap (& nums [i ], & nums [numsSize - 1 ]);
62
+
63
+ int rightSize = numsSize - i - 1 ; /* size of right sub array */
64
+
65
+ if (rightSize + 1 == k ) { /* found, it's pivot */
66
+ return nums [i ];
67
+ }
68
+
69
+ if (rightSize >= k ) {
70
+ return findKthLargest0 (nums + i + 1 , rightSize , k ); /* find in right half */
71
+ }
72
+ else {
73
+ return findKthLargest0 (nums , i , k - rightSize - 1 ); /* find in left half */
74
+ }
75
+ }
76
+
37
77
int main () {
38
78
39
79
int n [] = { 3 , 7 , 8 , 1 , 2 , 5 , 6 , 9 };
0 commit comments