Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created December 11, 2021 10:38
Show Gist options
  • Save mustafadalga/87cff9d84bad383471208c8074eafe39 to your computer and use it in GitHub Desktop.
Save mustafadalga/87cff9d84bad383471208c8074eafe39 to your computer and use it in GitHub Desktop.
Quick Sort Algorithm
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function pivot(arr, start = 0, end = arr.length + 1) {
var pivot = arr[start];
var swapIdx = start;
for (var i = start + 1; i < arr.length; i++) {
if (pivot > arr[i]) {
swapIdx++;
swap(arr, swapIdx, i);
}
}
swap(arr, start, swapIdx);
return swapIdx;
}
function quickSort(arr, left = 0, right = arr.length - 1) {
if (left < right) {
let pivotIndex = pivot(arr, left, right);
//left
quickSort(arr, left, pivotIndex - 1)
//right
quickSort(arr, pivotIndex + 1, right)
}
return arr;
}
const numberList = [...new Set(Array.from({ length: 50 }, () => Math.floor(Math.random() * 500 -250)))];
console.log(quickSort(numberList))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment