I tried to implement QuickSort algorithm from Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein - Introduction to Algorithms, Third Edition - 2009 * Section 7.1
in JavaScript.
So here is my implementation:
function swap(arr, i, j) {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function partition(arr, left = 0, right = arr.length - 1) {
let pivot = arr[right];
let i = left - 1;
let j;
for (j = left; j < right; j++) {
if (arr[j] < pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, right);
return i + 1;
}
function quickSort(arr, left = 0, right = arr.length - 1) {
if (left >= right) return arr;
const p = partition(arr, left, right);
quickSort(arr, left, p - 1);
quickSort(arr, p + 1, right);
return arr;
}
The problem with this code that it fails with stackoverflow error IF i pass already sorted array with length > 10 000
In case i pass array with fully random integers - everything working like expected even with 50 000 elements. So i can't understand is it problem with my code, or my node just can't handle such big call stack for worst-case quick sort usage.