一直觉得自己的数据结构学习的不是很好, 抽空练习练习下基础算法.
先来张图,了解下算法
cdn2.b0.upaiyun.com/2012/01/Visual-and-intuitive-feel-of-7-common-sorting-algorithms.gif">
算法比较简单, 就是在出栈的节点上想了半天,这点欢迎
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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。