-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0215-kth-largest-element-in-an-array.js
More file actions
66 lines (59 loc) · 1.67 KB
/
0215-kth-largest-element-in-an-array.js
File metadata and controls
66 lines (59 loc) · 1.67 KB
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
/**
* Kth Largest Element In An Array
* Time Complexity: O(N)
* Space Complexity: O(log N)
*/
var findKthLargest = function (nums, k) {
const arrayLength = nums.length;
const targetRank = arrayLength - k;
const swapElements = (arr, indexA, indexB) => {
const tempValue = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = tempValue;
};
const partitionArray = (currentArray, leftBound, rightBound) => {
const pivotElement = currentArray[rightBound];
let partitionPointer = leftBound;
for (
let currentElementIndex = leftBound;
currentElementIndex < rightBound;
currentElementIndex++
) {
if (currentArray[currentElementIndex] < pivotElement) {
swapElements(currentArray, partitionPointer, currentElementIndex);
partitionPointer++;
}
}
swapElements(currentArray, partitionPointer, rightBound);
return partitionPointer;
};
const performQuickSelect = (
dataset,
lowPointer,
highPointer,
requiredIndex,
) => {
if (lowPointer === highPointer) {
return dataset[lowPointer];
}
let actualPivotPosition = partitionArray(dataset, lowPointer, highPointer);
if (actualPivotPosition === requiredIndex) {
return dataset[actualPivotPosition];
} else if (requiredIndex < actualPivotPosition) {
return performQuickSelect(
dataset,
lowPointer,
actualPivotPosition - 1,
requiredIndex,
);
} else {
return performQuickSelect(
dataset,
actualPivotPosition + 1,
highPointer,
requiredIndex,
);
}
};
return performQuickSelect(nums, 0, arrayLength - 1, targetRank);
};