Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 02b1769

Browse files
Improvement
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 0e4fa45 commit 02b1769

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

0215_kth_largest_element_in_an_array/kth_elem.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ static void quick_select(int *nums, int lo, int hi, int k)
6262
* shall make the partition in the middle of the array as far as
6363
* possible. If the partition is located in the head or tail, the
6464
* performance might well be very bad for it.
65+
*
66+
* Note: Do NOT use nums[++i] <= pivot or nums[--j] >= pivot as the
67+
* loop condition because it leads to redundant operations in each
68+
* recusive iteration when there are many duplicate elements.
6569
*/
6670
while (i < hi && nums[++i] > pivot) {}
6771
while (j > lo && nums[--j] < pivot) {}
@@ -72,7 +76,8 @@ static void quick_select(int *nums, int lo, int hi, int k)
7276

7377
/* invariant: i == j + 1 or i == j */
7478
swap(&nums[i], &nums[hi]);
75-
if (i + 1 >= k) {
79+
/* compare index [i] with [k - 1] to locate the kth element */
80+
if (i > k - 1) {
7681
quick_select(nums, lo, i - 1, k);
7782
} else {
7883
quick_select(nums, i + 1, hi, k);

0 commit comments

Comments
 (0)