Visualize the Quicksort algorithm, known for its average-case efficiency.
Enter an array, select a pivot strategy, and click 'Start Sort'.
Quicksort is another efficient, comparison-based sorting algorithm that uses the Divide and Conquer strategy, but differently from Merge Sort:
function quickSort(arr, low, high) {
if (low < high) {
// pi is the partitioning index, arr[pi] is now at the right place
let pi = partition(arr, low, high);
// Recursively sort elements before partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Lomuto partition scheme
function partition(arr, low, high) {
// Choosing the last element as the pivot
let pivot = arr[high];
// Index of smaller element
let i = low - 1;
for (let j = low; j < high; j++) {
// If current element is smaller than the pivot
if (arr[j] < pivot) {
i++;
// Swap arr[i] and arr[j]
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// Swap arr[i+1] and arr[high] (put pivot in correct place)
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1; // Return the partition index
}
// Initial call:
// quickSort(myArray, 0, myArray.length - 1);