Golang快速排序
- User
Golang快速排序
Assistant
快速排序(QuickSort)是一种高效的排序算法,通过选择一个“基准”(pivot)元素,将数组分成两个子数组,一个子数组中的元素都比基准小,另一个子数组中的元素都比基准大,然后递归地对这两个子数组进行快速排序。
以下是用Go语言实现的快速排序算法:
package main import ( "fmt" ) // 快速排序函数 func quickSort(arr []int) []int { if len(arr) <= 1 { return arr } left, right := 0, len(arr)-1 pivotIndex := partition(arr, left, right) quickSort(arr[:pivotIndex]) quickSort(arr[pivotIndex+1:]) return arr } // 分区函数 func partition(arr []int, left int, right int) int { pivot := arr[right] i := left for j := left; j < right; j++ { if arr[j] <= pivot { arr[i], arr[j] = arr[j], arr[i] i++ } } arr[i], arr[right] = arr[right], arr[i] return i } func main() { arr := []int{10, 7, 8, 9, 1, 5} fmt.Println("排序前:", arr) sortedArr := quickSort(arr) fmt.Println("排序后:", sortedArr) }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.