Skip to content

Commit

Permalink
feat(core): add quick select
Browse files Browse the repository at this point in the history
  • Loading branch information
always-maap committed Oct 14, 2022
1 parent ea85845 commit 17a325d
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export * from './bubbleSort';
export * from './insertionSort';
export * from './linearSearch';
export * from './mergeSort';
export * from './quickSelect';
export * from './quickSort';
export * from './radixSort';
export * from './selectionSort';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/quickSelect/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { kthLargest, kthSmallest } from './quickSelect';
13 changes: 13 additions & 0 deletions packages/core/src/quickSelect/quickSelect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { kthLargest, kthSmallest } from './quickSelect';

describe('quickSelect', () => {
it('returns the kth largest element', () => {
const arr = [3, 2, 1, 5, 6, 4];
expect(kthLargest(arr, 2)).toBe(5);
});

it('returns the kth smallest element with duplicate inputs', () => {
const arr = [-1, -1, 0, 5, 12];
expect(kthSmallest(arr, 3)).toEqual(0);
});
});
31 changes: 31 additions & 0 deletions packages/core/src/quickSelect/quickSelect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function quickSelect(arr: number[], k: number, left = 0, right = arr.length - 1): number {
const pivot = arr[right];
let p = left;

for (let i = left; i < right; i++) {
if (arr[i] <= pivot) {
[arr[i], arr[p]] = [arr[p], arr[i]];
p++;
}
}

[arr[p], arr[right]] = [arr[right], arr[p]];

if (p === k) {
return arr[p];
}

if (p > k) {
return quickSelect(arr, k, left, p - 1);
} else {
return quickSelect(arr, k, p + 1, right);
}
}

export function kthLargest(arr: number[], k: number): number {
return quickSelect(arr, arr.length - k);
}

export function kthSmallest(arr: number[], k: number): number {
return quickSelect(arr, k - 1);
}

0 comments on commit 17a325d

Please sign in to comment.