Here's a clean, idiomatic Go implementation of the Quicksort algorithm:
go
package main
import (
"fmt"
)
func quicksort(arr []int) []int {
// Base case: if the slice has 0 or 1 elements, it's already sorted
if len(arr) <= 1 {
return arr
}
// Choose the pivot (middle element)
pivotIndex := len(arr) / 2
pivot := arr[pivotIndex]
// Partition the slice
var less, equal, greater []int
for _, num := range arr {
switch {
case num < pivot:
less = append(less, num)
case num == pivot:
equal = append(equal, num)
case num > pivot:
greater = append(greater, num)
}
}
// Recursively sort less and greater slices
// Combine the sorted slices
return append(
append(
quicksort(less),
equal...
),
quicksort(greater)...
)
}
func main() {
// Example usage
unsortedList := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Unsorted list:", unsortedList)
sortedList := quicksort(unsortedList)
fmt.Println("Sorted list: ", sortedList)
}
Key Go-Specific Features:
Slice Manipulation:
Uses Go's built-in slice operations
append() for adding elements
Spread operator ... for combining slices
In-Place Partitioning:
Creates separate slices for less, equal, and greater elements
Provides a clean, readable approach to partitioning
Recursive Implementation:
Leverages Go's efficient function calls
Uses middle element as pivot for better average-case performance
Performance Considerations:
Time Complexity: O(n log n) average case
Space Complexity: O(n) due to creating new slices
Not an in-place sort (creates new slices)
Variations You Might Want:
In-place quicksort
Pivot selection strategies
Generic implementation using interfaces
Would you like me to elaborate on any part of the implementation or discuss alternative sorting approaches in Go? 🚀
User
can you write a non recursive version
Assistant
Here's a non-recursive (iterative) implementation of Quicksort in Go using an explicit stack:
go
package main
import (
"fmt"
)
func quicksortIterative(arr []int) []int {
// Create a copy of the input slice to avoid modifying the original
nums := make([]int, len(arr))
copy(nums, arr)
// Create a stack to simulate recursion
stack := [][2]int{{0, len(nums) - 1}}
// Continue until the stack is empty
for len(stack) > 0 {
// Pop the top partition range
low, high := stack[len(stack)-1][0], stack[len(stack)-1][1]
stack = stack[:len(stack)-1]
// If the partition has more than one element
if low < high {
// Partition the slice
pivotIndex := partition(nums, low, high)
// Push left partition to stack
if pivotIndex > low {
stack = append(stack, [2]int{low, pivotIndex - 1})
}
// Push right partition to stack
if pivotIndex < high {
stack = append(stack, [2]int{pivotIndex + 1, high})
}
}
}
return nums
}
// Partition function using Lomuto partition scheme
func partition(arr []int, low, high int) int {
// Choose the rightmost element as pivot
pivot := arr[high]
// Index of smaller element
i := low - 1
// Traverse through all elements
// Compare each element with pivot
for j := low; j < high; j++ {
// If current element is smaller than or equal to pivot
if arr[j] <= pivot {
// Increment index of smaller element
i++
arr[i], arr[j] = arr[j], arr[i]
}
}
// Place pivot in correct position
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
}
func main() {
// Example usage
unsortedList := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Unsorted list:", unsortedList)
sortedList := quicksortIterative(unsortedList)
fmt.Println("Sorted list: ", sortedList)
}
Key Differences from Recursive Version:
Stack-Based Approach
Uses an explicit stack [][2]int to track partition ranges
Simulates recursive call stack manually
Avoids potential stack overflow for large lists
In-Place Sorting
Modifies the original slice directly
More memory-efficient than creating new slices
Uses Lomuto partition scheme
Performance Characteristics
Time Complexity: O(n log n) average case
Space Complexity: O(log n) for the stack
Avoids recursive function call overhead
Partition Strategy
Uses rightmost element as pivot
Moves smaller elements to the left
Ensures pivot is in its final sorted position
Advantages of Iterative Quicksort
Better memory management
Prevents potential stack overflow
More predictable performance for large datasets
Potential Improvements
Median-of-three pivot selection
Switching to insertion sort for small partitions
Handling edge cases more robustly
Would you like me to elaborate on any part of the implementation or discuss the nuances of the algorithm? 🚀