Quicksort partitions the input around a pivot and recursively sorts the two sides. This implementation uses the first value as its pivot. Balanced partitions give Θ(n log n) time. Repeatedly choosing an extreme value gives Θ(n²) time, including on already sorted input with this pivot rule.
Simple example
Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.
Start3 1 2
Result1 2 3
main.go
package main
import "fmt"
func main() {
values := []int{3, 1, 2}
pivot := values[2]
boundary := 0
i := 0
for i < 2 {
if values[i] < pivot {
saved := values[i]
values[i] = values[boundary]
values[boundary] = saved
boundary += 1
}
i += 1
}
values[2] = values[boundary]
values[boundary] = pivot
i = 0
for i < 3 {
fmt.Println(values[i])
i += 1
}
}
Output
1
2
3
Everyday examples
Divide parcels by a sample weight
Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?
Start8 2 5
Result2 • 5 • 8
Two is lighter and eight is heavier. The pivot now separates the two groups.
Handle equal book prices
Every book costs 4. What would a three-way partition produce?
Start4 4 4
Result∅ • 4 4 4 • ∅
The equal group contains every book. Neither outer group needs more work.
Notice a poor pivot
Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?
Start1 2 3 4
Result1 2 3 • 4 • ∅
One group still holds three items. Repeating this pattern wastes comparisons.
Cost and limits
Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).
Time Complexity
Best case: Θ(n log n)
Average case: Θ(n log n)
Worst case: Θ(n²)
Quick Sort Implementation in Go Programming
Golang source code
package main
import (
"fmt"
"strconv"
)
func quickSort(arr []int, low, high int) {
if low < high {
var pivot = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot + 1, high)
}
}
func partition(arr []int, low, high int) int {
var pivot = arr[low]
var i = low
var j = high
for i < j {
for arr[i] <= pivot && i < high {
i++;
}
for arr[j] > pivot && j > low {
j--
}
if i < j {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
arr[low] = arr[j]
arr[j] = pivot
return j
}
func printArray(arr []int) {
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, len(arr) - 1)
fmt.Print("After Sorting: ")
printArray(arr)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Advertisements
Walk through the example
Start with [15, 3, 12, 6, -9, 9, 0].
Use the first value, 15, as the pivot. Scan inward from both ends.
Advance the left index while its value is at most the pivot and the index is below the upper bound. Move the right index left while its value exceeds the pivot.
If the indices have not met, exchange the two misplaced values and continue scanning.
When the indices meet or cross, exchange the first value with the value at the right index. The pivot is now in its final position.
Recursively sort the ranges before and after that position. A range with fewer than two elements is already sorted.
Quick Sort Implementation in Go Programming with explanation
Golang source code
package main
import (
"fmt"
"strconv"
)
func quickSort(arr []int, low, high int) {
if low < high {
// Find the pivot index of the lower bound of an array
var pivot = partition(arr, low, high)
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
quickSort(arr, low, pivot - 1)
// Right hand side array
quickSort(arr, pivot + 1, high)
}
}
func partition(arr []int, low, high int) int {
// Pick a lowest bound element as an pivot value
var pivot = arr[low]
var i = low
var j = high
for i < j {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
for arr[i] <= pivot && i < high {
i++;
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
for arr[j] > pivot && j > low {
j--
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if i < j {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j]
arr[j] = pivot
// Finally return the appropriate index position of the pivot element
return j
}
func printArray(arr []int) {
// Loop the item and print each item in the console with white space seperated
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, len(arr) - 1)
fmt.Print("After Sorting: ")
printArray(arr)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15