here’s example of the quicksort algorithm implemented in Javascript:
function quickSort(arr) {
if (arr.length <= 1) return arr;
let pivot = arr[arr.length - 1];
let left = [];
let right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
This implementation of the QuickSort algorithm uses the last element of the input array as the pivot. The fucntion then uses a for-loop to iterate through the array, and for each element it compares it to the pivot. if the element is less than the pivot, it is added to the left
array, otherwise it is added to the right
array.
Once all the elements have been partitioned, the function recursively calls itself on the left
and right
arrays, and concatenates the result with the pivot. This process continues until the base case is reached, where the input array has only one element or no elements, in which case the function returns the input array.
Here's an example of how the function can be used:
let arr = [5, 3, 8, 4, 1, 9, -3];
console.log(quickSort(arr)); // [-3, 1, 3, 4, 5, 8, 9]