Created
January 10, 2014 19:40
-
-
Save jack-wong-build/8361178 to your computer and use it in GitHub Desktop.
Quick sort implementation in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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);
}
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
Do you really need to check if (leftIndex <= rightIndex) if the outer loop is already running while(leftIndex <= rightIndex)