package main
import(
"fmt"
)
func main() {
var arr [5]int = [5]int{11,13,9,2,25}
maopao(&arr)
fmt.Println("arr = ", arr) //[2 9 11 13 25]
findIndex := binaryFind(&arr, 0, len(arr) - 1, 25)
fmt.Println(findIndex)
}
func binaryFind(arr *[5]int, leftIndex int, rightIndex int, findVal int) int {
if leftIndex > rightIndex {
return -1
}
middleIndex := (leftIndex + rightIndex) / 2 //找中间下标
if (*arr)[middleIndex] > findVal { //说明findVal在左边
return binaryFind(arr, leftIndex, middleIndex - 1, findVal)
} else if (*arr)[middleIndex] < findVal { //说明findVal在右边
return binaryFind(arr, middleIndex + 1, rightIndex, findVal)
} else {
return middleIndex
}
}
func maopao(arr *[5]int) {
var temp int = 0 //临时变量做交换
len := len(arr)
for i := 0; i < len - 1; i++ { //外层循环长度减1
for j := 0; j < len - 1 - i; j++ {
if arr[j] > (*arr)[j+1] {
temp = (*arr)[j+1]
(*arr)[j+1] = (*arr)[j]
(*arr)[j] = temp
}
}
}
}
转载于:https://my.oschina.net/u/729139/blog/2099480