1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 // 二分查找函数 8 func search(bytes []int, target int, start int, end int) int { 9 pos := -1 10 for { 11 if bytes[start] == target { 12 pos = start 13 break 14 } 15 if bytes[end] == target { 16 pos = end 17 break 18 } 19 if start == end { 20 break 21 } 22 middle := (end + start) / 2 23 if target == bytes[middle] { 24 pos = middle 25 break 26 } else if target > bytes[middle] { 27 start = middle + 1 28 } else if target < bytes[middle] { 29 end = middle - 1 30 } 31 } 32 return pos 33 } 34 35 func main() { 36 bytes := []int{1, 5, 7, 9, 12, 15, 18, 25, 26, 33, 41, 47, 52, 62, 75, 84, 94, 100} 37 count := len(bytes) 38 fmt.Println(search(bytes, 33, 0, count-1)) 39 }