package main
import (
"fmt"
"math/rand"
"time"
)
const ( //常量
min, max = 0, 100
)
var (
A []int
C [max]int
n int
)
func Init(n int) bool { //初始化切片
if n > 0 {
rand := rand.New(rand.NewSource(time.Now().UnixNano())) //时间种子
for i := 0; i < n; i++ {
A = append(A, (rand.Intn(max-min) + min)) //生成随机数
}
return true
} else {
return false
}
}
func Count_Sort() []int {
fmt.Println(A)
B := make([]int, max, 2*max)
for j := 0; j < n; j++ {
C[A[j]] = C[A[j]] + 1
}
for i := 1; i < max; i++ {
C[i] = C[i] + C[i-1]
}
for j := n - 1; j >= 0; j-- {
B[C[A[j]]-1] = A[j]
C[A[j]] = C[A[j]] - 1
}
return B
}
func main() {
fmt.Println("请输入元素的个数:")
fmt.Scanln(&n)
if Init(n) {
t1 := time.Now()
fmt.Println(Count_Sort()[0:n])
elapsed := time.Since(t1)
fmt.Println("运行时间: ", elapsed)
} else {
fmt.Println("你输入的数据存在错误\a")
}
}
Go编写计数排序
最新推荐文章于 2023-08-07 00:22:02 发布