Skip to content

Commit f7a4b7d

Browse files
fix: Fix QuickSort (#207)
1 parent b72e357 commit f7a4b7d

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

sorts/quick_sort.ts

+26-18
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,39 @@ export const partition = (
1010
left: number = 0,
1111
right: number = array.length - 1
1212
) => {
13-
const pivot = array[Math.floor((right + left) / 2)];
14-
let i = left;
13+
const pivotIndex = choosePivot(left,right);
14+
const pivot = array[pivotIndex];
15+
[array[pivotIndex], array[right]] = [array[right], array[pivotIndex]];
16+
let i = left - 1;
1517
let j = right;
1618

17-
while (i <= j) {
18-
while (array[i] < pivot) {
19-
i++;
20-
}
21-
22-
while (array[j] > pivot) {
23-
j--;
24-
}
19+
while (i < j) {
20+
while (array[++i] < pivot);
21+
while (array[--j] > pivot);
2522

26-
if (i <= j) {
23+
if (i < j) {
2724
[array[i], array[j]] = [array[j], array[i]];
28-
i++;
29-
j--;
3025
}
3126
}
3227

28+
[array[right], array[i]] = [array[i], array[right]];
3329
return i;
3430
};
3531

32+
/**
33+
* @function choosePivot
34+
* @description Chooses a pivot element randomly within the subarray.
35+
* @param {number} left - The left index of the subarray.
36+
* @param {number} right - The right index of the subarray.
37+
* @returns {number} - The index of the chosen pivot element.
38+
*/
39+
const choosePivot = (
40+
left: number,
41+
right: number
42+
): number => {
43+
return Math.floor(Math.random() * (right - left + 1)) + left;
44+
};
45+
3646
/**
3747
* Quicksort implementation
3848
*
@@ -56,17 +66,15 @@ export const QuickSort = (
5666
left: number = 0,
5767
right: number = array.length - 1
5868
) => {
59-
let index;
60-
6169
if (array.length > 1) {
62-
index = partition(array, left, right);
70+
const index = partition(array, left, right);
6371

6472
if (left < index - 1) {
6573
QuickSort(array, left, index - 1);
6674
}
6775

68-
if (index < right) {
69-
QuickSort(array, index, right);
76+
if (index + 1 < right) {
77+
QuickSort(array, index + 1, right);
7078
}
7179
}
7280

0 commit comments

Comments
 (0)