Skip to content

Commit 63cc8a9

Browse files
committed
refactor(sorts): quicksort
1 parent d23d5f9 commit 63cc8a9

File tree

1 file changed

+23
-34
lines changed

1 file changed

+23
-34
lines changed

algorithms/sorts/quicksort.js

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,29 @@
1-
const swap = (arr, i, j) => {
2-
const temp = arr[i];
3-
arr[i] = arr[j];
4-
arr[j] = temp;
5-
};
6-
7-
const partition = (array, left, right) => {
8-
const pivot = array[Math.floor((right + left) / 2)];
9-
let i = left;
10-
let j = right;
11-
while (i <= j) {
12-
while (array[i] < pivot) {
13-
i++;
14-
}
15-
while (array[j] > pivot) {
16-
j--;
17-
}
18-
if (i <= j) {
19-
swap(array, i, j);
20-
i++;
21-
j--;
22-
}
1+
const QuickSort = (array) => {
2+
if (array.length <= 1) {
3+
return array;
234
}
24-
return i;
25-
};
265

27-
const sort = (array, left, right) => {
28-
if (array.length > 1) {
29-
const index = partition(array, left, right);
30-
if (left < index - 1) {
31-
sort(array, left, index - 1);
32-
}
33-
if (index < right) {
34-
sort(array, index, right);
6+
const leftArray = [];
7+
const rightArray = [];
8+
9+
const pivotElement = array.shift();
10+
const centerArray = [pivotElement];
11+
12+
while (array.length) {
13+
const currentElement = array.shift();
14+
if (currentElement === pivotElement) {
15+
centerArray.push(currentElement);
16+
} else if (currentElement < pivotElement) {
17+
leftArray.push(currentElement);
18+
} else {
19+
rightArray.push(currentElement);
3520
}
3621
}
37-
return array;
22+
23+
const leftArraySorted = QuickSort(leftArray);
24+
const rightArraySorted = QuickSort(rightArray);
25+
26+
return leftArraySorted.concat(centerArray, rightArraySorted);
3827
};
3928

40-
module.exports = sort;
29+
module.exports = QuickSort;

0 commit comments

Comments
 (0)