Quick Sort is an efficient sorting algorithm that follows the divide-and-conquer principle. In Go, we can implement Quick Sort to perform sorting operations efficiently on arrays and slices.
package main
import "fmt"
// quickSort function to sort an array
func quickSort(arr []int) []int {
if len(arr) < 2 {
return arr // Base case: arrays with 0 or 1 element are sorted
}
pivot := arr[0] // Choose the first element as the pivot
var less []int // Define a slice for less than pivot
var greater []int // Define a slice for greater than pivot
// Partitioning the array
for _, v := range arr[1:] {
if v <= pivot {
less = append(less, v)
} else {
greater = append(greater, v)
}
}
// Recursively apply quickSort to the partitions and concatenate results
return append(append(quickSort(less), pivot), quickSort(greater)...)
}
func main() {
arr := []int{3, 6, 8, 10, 1, 2, 1}
sortedArr := quickSort(arr)
fmt.Println("Sorted array:", sortedArr)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?