From 00d110fc985cd5bd5c6e7694397eebd0e5b3dbe7 Mon Sep 17 00:00:00 2001 From: hasan Date: Wed, 9 Jun 2021 15:47:52 +0600 Subject: [PATCH] Add doctest on quickselect algorithm --- Data-Structures/Array/QuickSelect.js | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Data-Structures/Array/QuickSelect.js b/Data-Structures/Array/QuickSelect.js index 7a90d2fcf4..9357ba3457 100644 --- a/Data-Structures/Array/QuickSelect.js +++ b/Data-Structures/Array/QuickSelect.js @@ -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"