An Implementation Of Quick Sort In JavaScript

/**
 * Sort an array using the quicksort algorithm.
 *
 * @param array array
 *   The array to sort.
 *
 * @returns
 *   The sorted array.
 */
function quickSort(array) {
  if (array.length === 0) {
    return array;
  }

  const k = array[0];
  const x = [];
  const y = [];

  for (let i = 1; i < array.length; i++) {
    if (array[i] <= k) {
      x.push(array[i]);
    } else {
      y.push(array[i]);
    }
  }
  return quickSort(x).concat([k]).concat(quickSort(y));
}

Run the fuction like this.

let mixed_numbers = [7, 1, 4];
quickSort(mixed_numbers);
console.log(mixed_numbers); // prints "[1, 4, 7]"

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
12 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.