Skip to content

Instantly share code, notes, and snippets.

@jesterswilde
Created June 26, 2019 23:27
Show Gist options
  • Save jesterswilde/85275cd367136708ce9426c4f7a87f1b to your computer and use it in GitHub Desktop.
Save jesterswilde/85275cd367136708ce9426c4f7a87f1b to your computer and use it in GitHub Desktop.
const quickSort = (array, left = 0, right)=>{
if(right === undefined){
right = array.length -1;
}
if(left >= right){
return;
}
moveMedian(array, left, right);
let wall = left;
const pivot = right;
for(let i = left; i < right; i++){
if(array[i] < array[pivot]){
swap(array, i, wall);
wall++;
}
}
swap(array, wall, pivot);
quickSort(array, left, wall-1);
quickSort(array, wall+1, right);
}
const moveMedian = (array, left, right)=>{
if(left === right - 1){
return;
}
const mid = Math.floor((left + right) / 2);
if(array[left] > array[mid]){
swap(array, left, mid);
}
if(array[mid] > array[right]){
swap(array, mid, right);
}
if(array[left] > array[mid]){
swap(array, left, mid);
}
swap(array, mid, right);
return;
}
const swap = (array, left, right)=>{
const temp = array[left];
array[left] = array[right];
array[right] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment