This post shows how to implement Quick Sort in JavaScript — another divide-and-conquer sorting algorithm, known for being fast in practice and a frequent "implement this algorithm" interview question.

Quick sort in JavaScript:

Explanation:
Quick sort picks a "pivot" element and partitions the rest of the array into two groups: elements smaller than the pivot and elements larger than it. It then recursively sorts each group. Unlike merge sort, quick sort typically sorts in place and doesn't need extra arrays for merging, which makes it faster in practice despite having the same O(n log n) average time complexity.


See Quick Sort in Action

Drag the slider to scrub through every comparison and partition step, or use Play to watch the pivot-based partitioning run automatically.


JavaScript Program to Implement Quick Sort

function quickSort(arr) {
  if (arr.length <= 1) return arr;

  const pivot = arr[arr.length - 1];
  const left = [];
  const right = [];

  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }

  return [...quickSort(left), pivot, ...quickSort(right)];
}

const numbers = [10, 7, 8, 9, 1, 5];
console.log("Sorted array:", quickSort(numbers));

Output:

Sorted array: [ 1, 5, 7, 8, 9, 10 ]

Quick sort is a favorite interview topic because of its elegant recursive partitioning — see more algorithm questions in our Interview Prep section, or try modifying the pivot selection yourself in our Code Runner.


Frequently Asked Questions About Quick Sort in JavaScript

What is the time complexity of quick sort?

Quick sort runs in O(n log n) time on average, but can degrade to O(n²) in the worst case (such as when the array is already sorted and the last element is always chosen as the pivot). Choosing a better pivot, like the middle element or a random one, helps avoid this.

Is quick sort faster than merge sort?

In practice, quick sort is often faster because it sorts in place and has smaller constant factors, even though both have the same average time complexity. Merge sort is preferred when stability or guaranteed worst-case performance matters more.

Why is pivot selection important in quick sort?

A poorly chosen pivot (like always picking the first or last element on nearly-sorted data) leads to unbalanced partitions and worst-case O(n²) performance. A good pivot keeps the two partitions roughly equal in size.