用golang写一个快速排序
时间: 2023-11-14 10:23:46 浏览: 107
以下是使用Golang编写的快速排序示例代码:
```
package main
import "fmt"
func quickSort(arr []int, left, right int) {
if left < right {
pivotIndex := partition(arr, left, right)
quickSort(arr, left, pivotIndex-1)
quickSort(arr, pivotIndex+1, right)
}
}
func partition(arr []int, left, right int) int {
pivot := arr[right]
i := left - 1
for j := left; j < right; j++ {
if arr[j] < pivot {
i++
arr[i], arr[j] = arr[j], arr[i]
}
}
arr[i+1], arr[right] = arr[right], arr[i+1]
return i + 1
}
func main() {
arr := []int{5, 3, 8, 6, 2, 7, 1, 4}
fmt.Println("Before sorting: ", arr)
quickSort(arr, 0, len(arr)-1)
fmt.Println("After sorting: ", arr)
}
```
输出:
```
Before sorting: [5 3 8 6 2 7 1 4]
After sorting: [1 2 3 4 5 6 7 8]
```
阅读全文