一直觉得自己的数据结构学习的不是很好, 抽空练习练习下基础算法.
先来张图,了解下算法
cdn2.b0.upaiyun.com/2012/01/Visual-and-intuitive-feel-of-7-common-sorting-algorithms.gif”>
这里是golang的代码实现,欢迎拍砖,
算法比较简单, 就是在出栈的节点上想了半天,这点欢迎
package main
import (
“fmt”
)
const (
greaterthan = iota //大于
equal // 等于
lessthan //小于
)
//比较
func comparedata(d1 int, d2 int) int {
if d1 < d2 {
return lessthan
} else if d1 == d2 {
return equal
} else {
return greaterthan
}
}
//交换
func swap(d1 *int, d2 *int) {
var temp int
temp = *d1
*d1 = *d2
*d2 = temp
return
}
//排序
func quicksort(datalist []int, left int, right int) {
var middle int
middle = (left + right) / 2
if middle == left {
return
}
if middle == right {
return
}
fmt.Println(“left “, left, “right “, right)
for i := left; i <= middle; i++ {
for j := middle; j <= right; j++ {
if comparedata(datalist[i], datalist[j]) == greaterthan {
swap(&datalist[i], &datalist[j])
}
}
}
if left < middle {
quicksort(datalist, left, middle)
}
if middle < right {
quicksort(datalist, middle, right)
}
}
func sort(datalist []int) {
quicksort(datalist, 0, len(datalist)-1)
fmt.Println(“数据:”)
fmt.Println(datalist)
}
const (
k = 200
)
func main() {
var (
datalist []int
)
datalist = make([]int, k)
for i := 0; i < k; i++ {
datalist[i] = 100 – i
}
datalist[1] = 101
datalist[2] = 103
datalist[8] = 200
datalist[6] = 201
datalist[4] = 204
datalist[5] = 206
datalist[3] = 207
datalist[9] = 2009
datalist[7] = 250
fmt.Println(datalist)
sort(datalist)
}
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/195006.html