function partition(arr, start, end) {
// Taking the last element as the pivot
const pivot = arr[end];
let p = start;
for (let i = start; i < end; i++) {
if (arr[i] < pivot) {
// Swapping elements
[arr[i], arr[p]] = [arr[p], arr[i]];
// Moving to next element
p++;
}
}
// Putting the pivot value in the middle
[arr[p], arr[end]] = [arr[end], arr[p]]
return p;
}
function quickSort(arr, start, end) {
// Base case or terminating case
if (start >= end) {
return;
}
// Returns pivotIndex
let pivotIndex = partition(arr, start, end);
// Recursively apply the same logic to the left and right subarrays
quickSort(arr, start, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, end);
}
array = [7, -2, 4, 1, 6, 5, 0, -4, 2];
quickSort(array, 0, array.length - 1);
console.log(array);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.