Add doctest on quickselect algorithm

This commit is contained in:
hasan
2021-06-09 15:47:52 +06:00
parent 194b11b35f
commit 00d110fc98

View File

@ -3,7 +3,7 @@
*
* Notes:
* -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
*
* @complexity: O(n) (on average )
@ -11,7 +11,11 @@
* @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)
}
@ -62,5 +66,13 @@ function Swap (arr, x, y) {
[arr[x], arr[y]] = [arr[y], arr[x]]
}
// testing
console.log(QuickSelect([1, 4, 2, -2, 4, 5]))
// > QuickSelect([1, 4, 2, -2, 4, 5], 1)
// -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"