# golang实现快排

datakv · · 5270 次点击 · · 开始浏览

```// QuickSort
package main

import (
"fmt"
"math/rand"
"time"
)

func swap(a int, b int) (int, int) {
return b, a
}

func partition(aris []int, begin int, end int) int {
pvalue := aris[begin]
i := begin
j := begin + 1
for j < end {
if aris[j] < pvalue {
i++
aris[i], aris[j] = swap(aris[i], aris[j])
}
j++
}
aris[i], aris[begin] = swap(aris[i], aris[begin])
return i
}

func quick_sort(aris []int, begin int, end int) {
if begin+1 < end {
mid := partition(aris, begin, end)
quick_sort(aris, begin, mid)
quick_sort(aris, mid+1, end)
}
}

func rand_array(aris []int, lent int) {
for i := 0; i < lent; i++ {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
aris[i] = r.Intn(1000)
}
}

func main() {
intas := []int{0, 0, 0, 0, 7, 20, 4, 77, 1, 22}
rand_array(intas, 10)
fmt.Println(intas)
quick_sort(intas, 0, 10)
fmt.Println(intas)
}```

1 回复  |  直到 2022-03-26 07:57:49

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传
```// QuickSort
package main

import (
"fmt"
"math/rand"
"time"
)

func swap(a int, b int) (int, int) {
return b, a
}

func partition(aris []int, begin int, end int) int {
pvalue := aris[begin]
i := begin
j := begin + 1
for j < end {
if aris[j] < pvalue {
i++
aris[i], aris[j] = swap(aris[i], aris[j])
}
j++
}
aris[i], aris[begin] = swap(aris[i], aris[begin])
return i
}

func quick_sort(aris []int, begin int, end int) {
if begin+1 < end {
mid := partition(aris, begin, end)
quick_sort(aris, begin, mid)
quick_sort(aris, mid+1, end)
}
}

func rand_array(aris []int, lent int) {
for i := 0; i < lent; i++ {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
aris[i] = r.Intn(1000)
}
}

func main() {
intas := []int{0, 0, 0, 0, 7, 20, 4, 77, 1, 22}
rand_array(intas, 10)
fmt.Println(intas)
quick_sort(intas, 0, 10)
fmt.Println(intas)
}```