标签:binary font search select ice head sel 查找 fun
1. 冒泡排序
func BubbleSort(slice []int) []int {
i, j, okay, count := 0, 0, true, len(slice)
for i = 0; i < count-1; i++ { //最多需要进行count-1轮比较
okay = true
for j = 0; j < count-i-1; j++ { //每一轮比较的逻辑
if slice[j] > slice[j+1] {
slice[j], slice[j+1] = slice[j+1], slice[j]
okay = false
}
}
if okay { //当轮比较没有发生位置交换,说明已经排序完成,可提前退出循环
break
}
}
return slice
}
2. 插入排序
func InsertSort(slice []int) []int {
var i, j int
count := len(slice)
for i = 1; i < count; i++ {
for j = i; j > 0; j-- { //通过比较,找插入位置
if slice[j-1] > slice[j] {
slice[j-1], slice[j] = slice[j], slice[j-1]
} else { //当前元素已找到插入位置,退出循环
break
}
}
}
return slice
}
3. 选择排序
func SelectSort(slice []int) []int {
var i, j, minKey int
count := len(slice)
for i = 0; i < count-1; i++ {
minKey = i
for j = i + 1; j < count; j++ { //找最小数位置
if slice[minKey] > slice[j] {
minKey = j
}
}
if minKey != i {
slice[minKey], slice[i] = slice[i], slice[minKey]
}
}
return slice
}
4. 快速排序
func QuickSort(slice []int, start, end int) {
if start >= end {
return
}
i, j := start, end
val := slice[(i+j)/2]
for i <= j {
for i <= end && slice[i] < val {
i++
}
for j >= start && slice[j] > val {
j--
}
if i <= j {
slice[i], slice[j] = slice[j], slice[i]
i++
j--
}
}
if start < j {
QuickSort(slice, start, j)
}
if end > i {
QuickSort(slice, i, end)
}
}
5. 二分查找
func BinarySearch(slice []int, head, tail, value int) int {
if head > tail {
return -1
}
middle := (head + tail) / 2
if slice[middle] == value {
return middle
} else if slice[middle] < value {
return BinarySearch(slice, middle+1, tail, value)
} else {
return BinarySearch(slice, head, middle-1, value)
}
}
标签:binary font search select ice head sel 查找 fun
原文地址:https://www.cnblogs.com/wujuntian/p/11612892.html