forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSelect.js
More file actions
Latest commit
65 lines (51 loc) · 1.62 KB
/
Copy pathQuickSelect.js
File metadata and controls
65 lines (51 loc) · 1.62 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
/**
* [QuickSelect](https://www.geeksforgeeks.org/quickselect-algorithm/) is an algorithm to find the kth smallest number
*
* Notes:
* -QuickSelect is related to QuickSort, thus has optimal best and average
* -case (O(n)) but unlikely poor worst case (O(n^2))
* -This implementation uses randomly selected pivots for better performance
*
* @complexity: O(n) (on average )
* @complexity: O(n^2) (worst case)
* @flow
*/
functionQuickSelect(items,kth){
// eslint-disable-line no-unused-vars
if(kth<1||kth>items.length){
thrownewRangeError('Index Out of Bound')
}
returnRandomizedSelect(items,0,items.length-1,kth)
}
functionRandomizedSelect(items,left,right,i){
if(left===right)returnitems[left]
constpivotIndex=RandomizedPartition(items,left,right)
constk=pivotIndex-left+1
if(i===k)returnitems[pivotIndex]
if(i<k)returnRandomizedSelect(items,left,pivotIndex-1,i)
returnRandomizedSelect(items,pivotIndex+1,right,i-k)
}
functionRandomizedPartition(items,left,right){
constrand=getRandomInt(left,right)
Swap(items,rand,right)
returnPartition(items,left,right)
}
functionPartition(items,left,right){
constx=items[right]
letpivotIndex=left-1
for(letj=left;j<right;j++){
if(items[j]<=x){
pivotIndex++
Swap(items,pivotIndex,j)
}
}
Swap(items,pivotIndex+1,right)
returnpivotIndex+1
}
functiongetRandomInt(min,max){
returnMath.floor(Math.random()*(max-min+1))+min
}
functionSwap(arr,x,y){
;[arr[x],arr[y]]=[arr[y],arr[x]]
}
export{QuickSelect}