Skip to content

Commit a70a829

Browse files
committed
randomly pick a pivot point
1 parent 2dc84a0 commit a70a829

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/array/kth-largest-element-in-an-array.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ const findKthLargest = (nums, k) => {
5151
};
5252

5353
const quickSelect = (nums, lo, hi, k) => {
54+
// speed up the quick sort
55+
// randomly pick a pivot point
56+
const p = Math.floor(Math.random() * (hi - lo + 1)) + lo;
57+
swap(nums, p, hi);
58+
5459
// use quick sort's idea
5560
// put nums that are <= pivot to the left
5661
// put nums that are > pivot to the right
@@ -61,7 +66,7 @@ const quickSelect = (nums, lo, hi, k) => {
6166
}
6267
swap(nums, i, j);
6368

64-
// count the nums that are <= pivot from lo
69+
// count the nums that are >= pivot
6570
const m = hi - i + 1;
6671
// pivot is the one!
6772
if (m === k) return nums[i];

0 commit comments

Comments
 (0)