Skip to content

Instantly share code, notes, and snippets.

@ButlerFuqua
Last active April 12, 2021 11:38
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 ButlerFuqua/2ba95ad99aac7aa58a673924ddfdb6d3 to your computer and use it in GitHub Desktop.
Save ButlerFuqua/2ba95ad99aac7aa58a673924ddfdb6d3 to your computer and use it in GitHub Desktop.
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