Complete the code to choose the pivot element as the last item in the array.
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[1];
// rest of the code
}The pivot is chosen as the last element, so we use arr[arr.length - 1].
Complete the code to partition the array by comparing elements to the pivot.
function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] [1] pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}We move elements less than or equal to the pivot to the left side.
Fix the error in the recursive quickSort call to sort left and right parts.
function quickSort(arr, low = 0, high = arr.length - 1) { if (low < high) { const pi = partition(arr, low, high); quickSort(arr, low, [1]); quickSort(arr, pi + 1, high); } return arr; }
We sort the left part from low to pi - 1 because pi is the pivot index.
Fill both blanks to complete the partition function's swap logic correctly.
function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
[arr[[1]], arr[[2]]] = [arr[[2]], arr[[1]]];
}
}
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}We swap elements at indices i and j to move smaller elements left.
Fill both blanks to complete the quickSort function with default parameters and recursive calls.
function quickSort(arr, [1] = 0, [2] = arr.length - 1) { if ([1] < [2]) { const pi = partition(arr, [1], [2]); quickSort(arr, [1], pi - 1); quickSort(arr, pi + 1, [2]); } return arr; }
pi with parameters.The parameters are low and high with default values. The recursive calls use low and high accordingly.
