Sort a Array with a QuickSort Function in JavaScript

Share this video with your friends

Send Tweet

Quicksort is a sorting algorithm that is much faster than selection sort. Quicksort involves working with two subarrays as well as a pivot item. When implemented properly it's on average Big O notation is O(n log n). Let’s explore this function and recreate it to sort a array within JavaScript!

Nicholas Murray
Nicholas Murray
~ 6 years ago

Hi Tyler, Firstly, excellent explanation of Big O notation in a relevant way to us JS devs. Secondly, what setup or plugin are you using to display the console logs inline in the editor for an unsaved file? Nicholas.

William Pei Yuan
William Pei Yuan
~ 6 years ago

@Nicholas, it's a vscode plugin called Quokka.js

tsvika
tsvika
~ 6 years ago

Why do you use for(let i in array) instead of forEach?

Anurag Bisht
Anurag Bisht
~ 6 years ago

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in

Using for...in to iterate over array eliminates the possibility of using strict type checking.

techtrainingAtshaadi
techtrainingAtshaadi
~ 5 years ago

here's a beautiful more functional version with ramda:

import { gt, partition } from "ramda";

function quickSort(list) {
  if (list.length === 0) {
    return list;
  } else {
    const [pivot, ...rest] = list;
    const [left, right] = partition(gt(pivot), rest);
    return [...quickSort(left), pivot, ...quickSort(right)];
  }
}

const result = quickSort([4, 7, 9, 1, 0, 8, 6, 10, 3, 8, 2, 5]);

console.log(result); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10]

https://codesandbox.io/s/quicksort-in-ramda-m4br7