Understanding Quick Sort Algorithm: Step-by-Step in JavaScript ??
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
Quick Sort is a sorting algorithm based on the Dividea and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.
function partition(arr, low, high) {
let pivot = arr[high];
let i = low - 1;
for (let j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
function swap(arr, i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function quickSort(arr, low, high) {
if (low < high) {
let pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
const arr = [64, 25, 12, 22, 11];
console.log("Original Array:", arr);
quickSort(arr, 0, arr.length - 1);
console.log("Sorted Array:", arr);