Skip to content

Commit

Permalink
Switch quicksort pivot selection strategy to random (#156)
Browse files Browse the repository at this point in the history
* feat: add Random Pivot Quick Sort

* feat: add Random Pivot for Quick Sort

* removed redundant export
  • Loading branch information
anshvert committed Oct 2, 2023
1 parent 24b02c1 commit 4db3278
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions sorts/quick_sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const partition = (
left: number = 0,
right: number = array.length - 1
) => {
const pivot = array[Math.floor((right + left) / 2)];
const pivot = array[choosePivot(left,right)];
let i = left;
let j = right;

Expand All @@ -33,6 +33,20 @@ export const partition = (
return i;
};

/**
* @function choosePivot
* @description Chooses a pivot element randomly within the subarray.
* @param {number} left - The left index of the subarray.
* @param {number} right - The right index of the subarray.
* @returns {number} - The index of the chosen pivot element.
*/
const choosePivot = (
left: number,
right: number
): number => {
return Math.floor(Math.random() * (right - left + 1)) + left
};

/**
* Quicksort implementation
*
Expand All @@ -55,7 +69,7 @@ export const QuickSort = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
): number[] => {
let index;

if (array.length > 1) {
Expand Down

0 comments on commit 4db3278

Please sign in to comment.