Created
December 11, 2021 10:38
-
-
Save mustafadalga/87cff9d84bad383471208c8074eafe39 to your computer and use it in GitHub Desktop.
Quick Sort Algorithm
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
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