Quicksort Algorithm

A divide-and-conquer sorting algorithm with O(n log n) average time complexity

Quicksort Implementation (JavaScript)

1function partition(arr, low, high) {
2  // Choosing the last element as the pivot
3  const pivot = arr[high];
4  let i = low - 1; // Index for smaller element
5
6  for (let j = low; j < high; j++) {
7    // If current element is smaller than the pivot
8    if (arr[j] < pivot) {
9      i++; // Increment index of smaller element
10      // Swap arr[i] and arr[j]
11      [arr[i], arr[j]] = [arr[j], arr[i]];
12    }
13  }
14  // Place the pivot element at its correct position
15  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
16  return i + 1; // Return the partition index
17}
18
19function quickSortRecursive(arr, low, high) {
20  if (low < high) {
21    // pi is the partitioning index, arr[pi] is now at the right place
22    const pi = partition(arr, low, high);
23
24    // Separately sort elements before partition and after partition
25    quickSortRecursive(arr, low, pi - 1);
26    quickSortRecursive(arr, pi + 1, high);
27  }
28  return arr;
29}
30
31// Initial call
32// let myArray = [10, 7, 8, 9, 1, 5];
33// quickSortRecursive(myArray, 0, myArray.length - 1);
34// console.log("Sorted array:", myArray);