Skip to content

Commit 580c208

Browse files
authored
Add in-place sort to QuickSort.js
1 parent f696d02 commit 580c208

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/algorithms/sorting/quick-sort/QuickSort.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,66 @@ export default class QuickSort extends Sort {
4141
// Let's now join sorted left array with center array and with sorted right array.
4242
return leftArraySorted.concat(centerArray, rightArraySorted);
4343
}
44+
45+
/*
46+
While not always appropriate for the job at hand, if you don't mind modifying the input array,
47+
sorting in place offers space benefits, and while it doesn't change the time comlexity, it is
48+
usually more performant
49+
*/
50+
sortInPlace(array, low, high) {
51+
52+
// Helper function
53+
const partition = (arr, l, h) => {
54+
55+
// Helper function
56+
const swap = (a, left, right) => {
57+
const tempVariable = a[left];
58+
a[left] = a[right];
59+
a[right] = tempVariable;
60+
}
61+
62+
const pivot = arr[h];
63+
let firstRunner = l - 1;
64+
65+
for (let secondRunner = l; secondRunner < h; secondRunner += 1) {
66+
/*
67+
If `secondRunner` - `firstRunner` is 1, then element at index `secondRunner` swaps with itself. Regardless, swapping
68+
elements increments firstRunner
69+
*/
70+
if (arr[secondRunner] < pivot) {
71+
firstRunner += 1;
72+
swap(arr, firstRunner, secondRunner);
73+
}
74+
}
75+
76+
/*
77+
This process is difficult to describe, but much clearer with a visualization:
78+
http://www.algomation.com/algorithm/quick-sort-visualization
79+
*/
80+
if (arr[firstRunner + 1] > pivot) {
81+
swap(arr, firstRunner + 1, h);
82+
}
83+
84+
return firstRunner + 1;
85+
};
86+
87+
/*
88+
While we can use a default parameter to set `low` to 0, we would still have to set `high`'s default within the function
89+
as we don't have access to `array.length - 1` when declaring paramaters
90+
*/
91+
low = low === undefined ? 0 : low;
92+
high = high === undefined ? array.length - 1 : high;
93+
94+
// Base case is when low and high converge
95+
if (low < high) {
96+
const partitionIndex = partition(array, low, high);
97+
/*
98+
`partition()` swaps elements of the array based on their comparison to the `hi` parameter, and then returns the index
99+
where swapping is no longer necessary, which can be best thought of as the pivot used to split an array in a
100+
non-in-place quicksort
101+
*/
102+
this.sortInPlace(array, low, partitionIndex - 1);
103+
this.sortInPlace(array, partitionIndex + 1, high);
104+
}
105+
}
44106
}

0 commit comments

Comments
 (0)