Skip to content

Commit 4db3278

Browse files
authored
Switch quicksort pivot selection strategy to random (TheAlgorithms#156)
* feat: add Random Pivot Quick Sort * feat: add Random Pivot for Quick Sort * removed redundant export
1 parent 24b02c1 commit 4db3278

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

sorts/quick_sort.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export const partition = (
1010
left: number = 0,
1111
right: number = array.length - 1
1212
) => {
13-
const pivot = array[Math.floor((right + left) / 2)];
13+
const pivot = array[choosePivot(left,right)];
1414
let i = left;
1515
let j = right;
1616

@@ -33,6 +33,20 @@ export const partition = (
3333
return i;
3434
};
3535

36+
/**
37+
* @function choosePivot
38+
* @description Chooses a pivot element randomly within the subarray.
39+
* @param {number} left - The left index of the subarray.
40+
* @param {number} right - The right index of the subarray.
41+
* @returns {number} - The index of the chosen pivot element.
42+
*/
43+
const choosePivot = (
44+
left: number,
45+
right: number
46+
): number => {
47+
return Math.floor(Math.random() * (right - left + 1)) + left
48+
};
49+
3650
/**
3751
* Quicksort implementation
3852
*
@@ -55,7 +69,7 @@ export const QuickSort = (
5569
array: number[],
5670
left: number = 0,
5771
right: number = array.length - 1
58-
) => {
72+
): number[] => {
5973
let index;
6074

6175
if (array.length > 1) {

0 commit comments

Comments
 (0)