chore: merged "Quick select tests" (#697)

* add link to function description

* fix formatting for consistency

* export function so it can be imported for testing

* throw error on invalid input

* add tests for QuickSelect.js

* remove unnecessary comment

* Update Data-Structures/Array/QuickSelect.js

Co-authored-by: Rak Laptudirm <raklaptudirm@gmail.com>

Co-authored-by: Rak Laptudirm <raklaptudirm@gmail.com>
This commit is contained in:
Charlie Moore
2021-09-27 12:14:11 -04:00
committed by GitHub
parent 36603e7382
commit f071220c3e
2 changed files with 54 additions and 8 deletions

View File

@ -1,5 +1,5 @@
/**
* QuickSelect is an algorithm to find the kth smallest number
* [QuickSelect](https://www.geeksforgeeks.org/quickselect-algorithm/) is an algorithm to find the kth smallest number
*
* Notes:
* -QuickSelect is related to QuickSort, thus has optimal best and average
@ -13,18 +13,13 @@
function QuickSelect (items, kth) { // eslint-disable-line no-unused-vars
if (kth < 1 || kth > items.length) {
return 'Index Out of Bound'
throw new RangeError('Index Out of Bound')
}
return RandomizedSelect(items, 0, items.length - 1, kth)
}
function RandomizedSelect (
items,
left,
right,
i
) {
function RandomizedSelect (items, left, right, i) {
if (left === right) return items[left]
const pivotIndex = RandomizedPartition(items, left, right)
@ -76,3 +71,5 @@ function Swap (arr, x, y) {
// "Index Out of Bound"
// > QuickSelect([1, 4, 2, -2, 4, 5], 7)
// "Index Out of Bound"
export { QuickSelect }