I used timothy roughgardens partition where he chooses the first element, but it doesn't quite work the way I want it to.
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(arr, left, right) {
left = left || 0;
right = right || arr.length - 1;
var pivot = arr[0];
var i = left + 1;
for (var j = left + 1; j < right; j++) {
if (arr[j] < pivot) {
swap(arr, j, i); //need to swap with left most array entry which is currently bigger than pivot
i++;
}
}
//swap pivot with right most element smaller than the pivot (i-1)
swap(arr, left, i-1)
// console.log(arr);
// return i;
return i - 1;
}
function quickSort(arr, start, end) {
start = start || 0;
end = end || arr.length - 1;
var pivotNewIndex = partition(arr, start, end);
if (start < end) {
quickSort(arr, start, pivotNewIndex - 1);
quickSort(arr, pivotNewIndex + 1, end);
}
return arr;
}
var arr4 = [3, 8, 2, 1, 5];
console.log(quickSort(arr4)); --- > [ 1, 2, 3, 8, 5 ];
what am I doing wrong here? I think end is getting reassigned from the original end, how do i stop that