mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Add doctest on quickselect algorithm
This commit is contained in:
@ -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"
|
||||
|
Reference in New Issue
Block a user