Skip to content

Quick sort implementation

Daisho Komiyama edited this page Jun 19, 2021 · 1 revision

Quicksort is one of the most useful and powerful sorting algorithms out there, and it's not terribly difficult to conceptualize.

The basic gist is that you take the last element in the list and call that the pivot. Everything that's smaller than the pivot gets put into a "left" list and everything that's greater get's put in a "right" list. You then call quick sort on the left and right lists independently (hence the recursion.)

const quickSort = nums => {
  if (nums.length <= 1) {
    return nums
  }

  const pivot = nums[nums.length - 1]
  const left = []
  const right = []
  
  for (let i = 0; i < nums.length - 1; i++) {
    if (nums[i] < pivot) {
      left.push(nums[i])
    } else {
      right.push(nums[i])
    }
  }
 
  return [...quickSort(left), pivot, ...quickSort(right)]
}
Clone this wiki locally