We are required to write a JavaScript function that takes in an array of Numbers. The function should apply the algorithm of quicksort to sort the array either in increasing or decreasing order.
QuickSort Algorithm
Quicksort follows the below steps −
Step 1 − Make any element as the pivot (preferably first or last, but any element can be the pivot)
Step 2 − Partition the array on the basis of pivot
Step 3 − Apply a quick sort on the left partition recursively
Step 4 − Apply a quick sort on the right partition recursively
The average and best case time complexity of QuickSort are O(nlogn) whereas in worst cases, it can slow up to O(n^2).
Example
The code for this will be −
const arr = [5,3,7,6,2,9]; const swap = (arr, leftIndex, rightIndex) => { let temp = arr[leftIndex]; arr[leftIndex] = arr[rightIndex]; arr[rightIndex] = temp; }; const partition = (arr, left, right) => { let pivot = arr[Math.floor((right + left) / 2)]; let i = left; let j = right; while (i <= j) { while (arr[i] < pivot) { i++; }; while (arr[j] > pivot) { j--; }; if (i <= j) { swap(arr, i, j); //sawpping two elements i++; j--; }; }; return i; } const quickSort = (arr, left = 0, right = arr.length - 1) => { let index; if (arr.length > 1) { index = partition(arr, left, right); if (left < index - 1) { quickSort(arr, left, index - 1); }; if (index < right) { quickSort(arr, index, right); }; } return arr; } let sortedArray = quickSort(arr); console.log(sortedArray);
Output
And the output in the console will be −
[ 2, 3, 5, 6, 7, 9 ]