mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Add doctest on quickselect algorithm
This commit is contained in:
@ -3,7 +3,7 @@
|
|||||||
*
|
*
|
||||||
* Notes:
|
* Notes:
|
||||||
* -QuickSelect is related to QuickSort, thus has optimal best and average
|
* -QuickSelect is related to QuickSort, thus has optimal best and average
|
||||||
* case (O(n)) but unlikely poor worst case (O(n^2))
|
* -case (O(n)) but unlikely poor worst case (O(n^2))
|
||||||
* -This implementation uses randomly selected pivots for better performance
|
* -This implementation uses randomly selected pivots for better performance
|
||||||
*
|
*
|
||||||
* @complexity: O(n) (on average )
|
* @complexity: O(n) (on average )
|
||||||
@ -11,7 +11,11 @@
|
|||||||
* @flow
|
* @flow
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function QuickSelect (items, kth) {
|
function QuickSelect (items, kth) { // eslint-disable-line no-unused-vars
|
||||||
|
if (kth < 1 || kth > items.length) {
|
||||||
|
return 'Index Out of Bound'
|
||||||
|
}
|
||||||
|
|
||||||
return RandomizedSelect(items, 0, items.length - 1, kth)
|
return RandomizedSelect(items, 0, items.length - 1, kth)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -62,5 +66,13 @@ function Swap (arr, x, y) {
|
|||||||
[arr[x], arr[y]] = [arr[y], arr[x]]
|
[arr[x], arr[y]] = [arr[y], arr[x]]
|
||||||
}
|
}
|
||||||
|
|
||||||
// testing
|
// > QuickSelect([1, 4, 2, -2, 4, 5], 1)
|
||||||
console.log(QuickSelect([1, 4, 2, -2, 4, 5]))
|
// -2
|
||||||
|
// > QuickSelect([1, 4, 2, -2, 4, 5], 5)
|
||||||
|
// 4
|
||||||
|
// > QuickSelect([1, 4, 2, -2, 4, 5], 6)
|
||||||
|
// 5
|
||||||
|
// > QuickSelect([1, 4, 2, -2, 4, 5], 0)
|
||||||
|
// "Index Out of Bound"
|
||||||
|
// > QuickSelect([1, 4, 2, -2, 4, 5], 7)
|
||||||
|
// "Index Out of Bound"
|
||||||
|
Reference in New Issue
Block a user