Created
April 28, 2021 19:12
-
-
Save christopher-caldwell/ef6dc54d4d18fbb1df82506ca7450de2 to your computer and use it in GitHub Desktop.
WIP implementation of a Quick Sort algorithm
This file contains hidden or 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
const baseArray = [ | |
{value: 1}, | |
{value: 4}, | |
{value: 8}, | |
{value: 9}, | |
{value: 7}, | |
{value: 2}, | |
{value: 3}, | |
{value: 5}, | |
{value: 6}, | |
] | |
const findMiddleIndexOfPartition = (leftIndex, rightIndex) => { | |
return Math.floor((leftIndex + rightIndex) / 2) | |
} | |
const swapElements = (arr, leftPointer, iterator) => { | |
// capturing the value of the left pointer | |
let temp = arr[leftPointer] | |
arr[leftPointer] = arr[iterator] | |
arr[iterator] = temp | |
} | |
const determinePartitionIndexPosition = (items, leftIndex, rightIndex, objectPropertyToSortBy) => { | |
const pivotIndex = findMiddleIndexOfPartition(leftIndex, rightIndex) | |
const pivotItem = items[pivotIndex][objectPropertyToSortBy] | |
let leftIndexPointer = leftIndex | |
let rightIndexPointer = rightIndex | |
while (leftIndexPointer <= rightIndexPointer) { | |
while (items[leftIndexPointer][objectPropertyToSortBy] < pivotItem) { | |
leftIndexPointer++; | |
} | |
while (items[rightIndexPointer][objectPropertyToSortBy] > pivotItem) { | |
rightIndexPointer--; | |
} | |
if (leftIndexPointer <= rightIndexPointer) { | |
// promise.all | |
swapElements(items, leftIndexPointer, rightIndexPointer); | |
leftIndexPointer++; | |
rightIndexPointer--; | |
} | |
} | |
return leftIndexPointer; | |
} | |
const quickSortCenterPartition = (items, leftIndex, rightIndex, objectPropertyToSortBy) => { | |
let index | |
if (items.length > 1) { | |
index = determinePartitionIndexPosition(items, leftIndex, rightIndex, objectPropertyToSortBy); //index returned from partition | |
if (leftIndex < index - 1) { //more elements on the left side of the pivot | |
quickSortCenterPartition(items, leftIndex, index - 1, objectPropertyToSortBy); | |
} | |
if (index < rightIndex) { //more elements on the right side of the pivot | |
quickSortCenterPartition(items, index, rightIndex, objectPropertyToSortBy); | |
} | |
} | |
return items; | |
} | |
console.log(quickSortCenterPartition(baseArray, 0, baseArray.length - 1, 'value')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment