Skip to content

Commit 5c691ba

Browse files
committed
refactored quick sort iterative.
1 parent 2722dca commit 5c691ba

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

src/_.general/sorting.js

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -176,29 +176,26 @@ export function quickSortWithArray(array) {
176176
* @return {Array}
177177
*
178178
*/
179-
export function quickSort(array, lo, hi) {
179+
export function quickSort(array, lo = 0, hi = array.length) {
180180
checkArray(array);
181-
lo = typeof lo === "number" ? lo : 0;
182-
hi = typeof hi === "number" ? hi : array.length;
183-
if (hi <= lo) return array;
181+
if (array.length <= 1 || hi <= lo) return array;
184182

185183
const partition = (arr, left, right) => {
186-
let start = left;
187-
let end = right;
184+
let i = left;
185+
let j = right;
188186
const pivot = arr[left];
189187

190-
while (start < end) {
191-
while (arr[++start] <= pivot) if (start === right) break; // eslint-disable-line no-plusplus
192-
while (arr[--end] >= pivot) if (end === left) break; // eslint-disable-line no-plusplus
193-
if (start >= end) break;
194-
swap(arr, start, end);
188+
while (i < j) {
189+
while (arr[++i] <= pivot) if (i === right) break; // eslint-disable-line no-plusplus
190+
while (arr[--j] >= pivot) if (j === left) break; // eslint-disable-line no-plusplus
191+
if (i < j) swap(arr, i, j);
195192
}
196-
swap(arr, left, end);
197-
return end;
193+
swap(arr, left, j);
194+
return j;
198195
};
199-
const pivot = partition(array, lo, hi);
200-
quickSort(array, lo, pivot);
201-
quickSort(array, pivot + 1, hi);
196+
const pivotIndex = partition(array, lo, hi);
197+
quickSort(array, lo, pivotIndex);
198+
quickSort(array, pivotIndex + 1, hi);
202199

203200
return array;
204201
}

0 commit comments

Comments
 (0)