Skip to content

Instantly share code, notes, and snippets.

@FergusDevelopmentLLC
Last active March 19, 2021 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FergusDevelopmentLLC/d93428483451beb33c5f8e90fda895e9 to your computer and use it in GitHub Desktop.
Save FergusDevelopmentLLC/d93428483451beb33c5f8e90fda895e9 to your computer and use it in GitHub Desktop.
quickSort.js
const quickSort = (targetArray, lowIndex, highIndex) => {
const swap = (targetArray, lowIndex, highIndex) => {
let temp = targetArray[lowIndex]
targetArray[lowIndex] = targetArray[highIndex]
targetArray[highIndex] = temp
}
//pivotElement will be the value of the element closest to the middle of the array
let pivotElement = targetArray[Math.floor((highIndex + lowIndex) / 2)]//middle element
//at the start, set leftPointer to lowIndex
let leftPointer = lowIndex
//at the start, st rightPointer to highIndex
let rightPointer = highIndex
//the outer while loop contines until the pointers converge and are equal
while (leftPointer <= rightPointer) {
while (targetArray[leftPointer] < pivotElement) {
leftPointer++
}
while (targetArray[rightPointer] > pivotElement) {
rightPointer--
}
if (leftPointer <= rightPointer) {
swap(targetArray, leftPointer, rightPointer) //swap two elements
leftPointer++
rightPointer--
}
}
//more elements on the left side of the pivot
if (lowIndex < leftPointer - 1) {
quickSort(targetArray, lowIndex, leftPointer - 1)
}
//more elements on the right side of the pivot
if (leftPointer < highIndex) {
quickSort(targetArray, leftPointer, highIndex)
}
return targetArray
}
//the array to sort
const unsortedArray = [7, 0, 2, 1, 9, 2]
console.log('unsortedArray', unsortedArray)
//set a lowIndex for the index of the first element
const lowIndex = 0
//set highIndex, for the index of the last element
const highIndex = unsortedArray.length - 1
//we have to set these as variables, because quicksort is a recursive function
//pass in the unsorted array, lowIndex and highIndex to quickSort function
const sorted = quickSort(unsortedArray, lowIndex, highIndex)
//display sorted array
console.log('sorted', sorted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment