We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0e4fa45 commit 02b1769Copy full SHA for 02b1769
0215_kth_largest_element_in_an_array/kth_elem.c
@@ -62,6 +62,10 @@ static void quick_select(int *nums, int lo, int hi, int k)
62
* shall make the partition in the middle of the array as far as
63
* possible. If the partition is located in the head or tail, the
64
* 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.
69
*/
70
while (i < hi && nums[++i] > pivot) {}
71
while (j > lo && nums[--j] < pivot) {}
@@ -72,7 +76,8 @@ static void quick_select(int *nums, int lo, int hi, int k)
72
76
73
77
/* invariant: i == j + 1 or i == j */
74
78
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) {
81
quick_select(nums, lo, i - 1, k);
82
} else {
83
quick_select(nums, i + 1, hi, k);
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments