Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created January 10, 2014 19:40
Show Gist options
  • Save jack-wong-build/8361178 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8361178 to your computer and use it in GitHub Desktop.
Quick sort implementation in JavaScript.
var quickSort = function(array, left, right){
var leftIndex = partition(array, left, right);
if (left < leftIndex - 1){
quickSort(array, left, leftIndex-1);
}
if (right > leftIndex){
quickSort(array, leftIndex, right);
}
return array;
}
var swap = function(array, left, right){
var temp;
temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
var partition = function(array, left, right){
var pivotIndex = Math.floor( (left + right) / 2);
var pivot = array[pivotIndex];
leftIndex = left;
rightIndex = right;
while (leftIndex <= rightIndex){
while(array[leftIndex] < pivot){
leftIndex++;
}
while(array[rightIndex] > pivot){
rightIndex--;
}
if (leftIndex <= rightIndex){
swap(array, left, right);
leftIndex++;
rightIndex--;
}
}
return leftIndex;
}
@jchaplin2
Copy link

Do you really need to check if (leftIndex <= rightIndex) if the outer loop is already running while(leftIndex <= rightIndex)

@didi-rare
Copy link

didi-rare commented Jun 23, 2019

Here is the JavaScript recursive implementation.

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

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

    return quickSort(left).concat(pivot, right);
}

You could even do this by utilizing the array filter method.

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

    const pivot = arr[0], left = [], right = [];
    const restArray = arr.slice(1);
    restArray.filter(value => {
        if (value < pivot) {
            left.push(value);
        } else {
            right.push(value);
        }
    });

    return quickSort(left).concat(pivot, right);
}

@didi-rare
Copy link

You could even do this by utilizing JavaScript array filter method.

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

    const pivot = arr[0], left = [], right = [];
    const restArray = arr.slice(1);
    restArray.filter(value => {
        if (value < pivot) {
            left.push(value);
        } else {
            right.push(value);
        }
    });

    return quickSort(left).concat(pivot, right);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment