Skip to content

Commit cc9bed4

Browse files
committed
Add doctest on quickselect algorithm
1 parent 194b11b commit cc9bed4

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

Data-Structures/Array/QuickSelect.js

+16-4
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,19 @@
33
*
44
* Notes:
55
* -QuickSelect is related to QuickSort, thus has optimal best and average
6-
* case (O(n)) but unlikely poor worst case (O(n^2))
6+
* -case (O(n)) but unlikely poor worst case (O(n^2))
77
* -This implementation uses randomly selected pivots for better performance
88
*
99
* @complexity: O(n) (on average )
1010
* @complexity: O(n^2) (worst case)
1111
* @flow
1212
*/
1313

14-
function QuickSelect (items, kth) {
14+
function QuickSelect (items, kth) { // eslint-disable-line no-unused-vars
15+
if (kth < 1 || kth > items.length) {
16+
return 'Index Out of Bound'
17+
}
18+
1519
return RandomizedSelect(items, 0, items.length - 1, kth)
1620
}
1721

@@ -62,5 +66,13 @@ function Swap (arr, x, y) {
6266
[arr[x], arr[y]] = [arr[y], arr[x]]
6367
}
6468

65-
// testing
66-
console.log(QuickSelect([1, 4, 2, -2, 4, 5]))
69+
// > QuickSelect([1, 4, 2, -2, 4, 5], 1)
70+
// -2
71+
// > QuickSelect([1, 4, 2, -2, 4, 5], 5)
72+
// 4
73+
// > QuickSelect([1, 4, 2, -2, 4, 5], 6)
74+
// 5
75+
// > QuickSelect([1, 4, 2, -2, 4, 5], -1)
76+
// "Index Out of Bound"
77+
// > QuickSelect([1, 4, 2, -2, 4, 5], 7)
78+
// "Index Out of Bound"

0 commit comments

Comments
 (0)