Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions Data-Structures/Array/QuickSelect.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@
*
* 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 )
* @complexity: O(n^2) (worst case)
* @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)
}

Expand Down Expand Up @@ -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"