Last active
April 12, 2021 11:38
-
-
Save ButlerFuqua/2ba95ad99aac7aa58a673924ddfdb6d3 to your computer and use it in GitHub Desktop.
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
Partition(numbers, lowIndex, highIndex) { | |
// Pick middle element as pivot | |
midpoint = lowIndex + (highIndex - lowIndex) / 2 | |
pivot = numbers[midpoint] | |
done = false | |
while (!done) { | |
// Increment lowIndex while numbers[lowIndex] < pivot | |
while (numbers[lowIndex] < pivot) { | |
lowIndex += 1 | |
} | |
// Decrement highIndex while pivot < numbers[highIndex] | |
while (pivot < numbers[highIndex]) { | |
highIndex -= 1 | |
} | |
// If zero or one elements remain, then all numbers are | |
// partitioned. Return highIndex. | |
if (lowIndex >= highIndex) { | |
done = true | |
} | |
else { | |
// Swap numbers[lowIndex] and numbers[highIndex] | |
temp = numbers[lowIndex] | |
numbers[lowIndex] = numbers[highIndex] | |
numbers[highIndex] = temp | |
// Update lowIndex and highIndex | |
lowIndex += 1 | |
highIndex -= 1 | |
} | |
} | |
return highIndex | |
} | |
Quicksort(numbers, lowIndex, highIndex) { | |
// Base case: If the partition size is 1 or zero | |
// elements, then the partition is already sorted | |
if (lowIndex >= highIndex) { | |
return | |
} | |
// Partition the data within the array. Value lowEndIndex | |
// returned from partitioning is the index of the low | |
// partition's last element. | |
lowEndIndex = Partition(numbers, lowIndex, highIndex) | |
// Recursively sort low partition (lowIndex to lowEndIndex) | |
// and high partition (lowEndIndex + 1 to highIndex) | |
Quicksort(numbers, lowIndex, lowEndIndex) | |
Quicksort(numbers, lowEndIndex + 1, highIndex) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment