This is the quicksort algorithm I wrote:
var arr = [0, 2, 5, 10, 3, 22, 12, 8, 20];
let quickSort = (arr) => {
let len = arr.length;
if (len === 1) {
return arr;
};
let pivot = arr.length - 1;
const rightArr = [];
const leftArr = [];
for (let i = 0; i < len - 1; i++) {
let j = i + 1;
if (arr[j] > arr[pivot]) {
rightArr.push(arr[j]);
} else {
leftArr.push(arr[j]);
};
};
if (leftArr.length > 0 && rightArr.length > 0) {
return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
} else if (leftArr.length > 0 && rightArr.length <= 0) {
return [...quickSort(leftArr), pivot];
} else {
return [pivot, ...quickSort(rightArr)];
};
};
console.log(quickSort(arr));
The output is: [20, 1, 2, 3, 4, 5, 6, 8, 22]
My question is: why do I get the wrong output and how do I fix this ?
forloop skipsarr[0].pivotto the list instead ofarr[pivot], pivot being the index