mirror of
https://github.com/0xAX/go-algorithms
synced 2024-11-11 19:10:39 +00:00
binary search
This commit is contained in:
parent
f7794af38d
commit
192c15d936
BIN
searching/binarySearch
Executable file
BIN
searching/binarySearch
Executable file
Binary file not shown.
45
searching/binarySearch.go
Normal file
45
searching/binarySearch.go
Normal file
@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
//import "sort"
|
||||
|
||||
func main() {
|
||||
searchValue := 0
|
||||
|
||||
arr := [10]int{1, 5, 100, 0, -100, 15, 4, 102, 30, 1000}
|
||||
|
||||
tmp := 0
|
||||
|
||||
for i := 0; i < len(arr); i++ {
|
||||
for j := 0; j < len(arr) - 1; j++ {
|
||||
if arr[j] > arr[j + 1] {
|
||||
tmp = arr[j]
|
||||
arr[j] = arr[j + 1]
|
||||
arr[j + 1] = tmp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
left := 0
|
||||
right := len(arr) - 1
|
||||
|
||||
if right < left {
|
||||
fmt.Println("Not found")
|
||||
return
|
||||
}
|
||||
|
||||
for ; left <= right ; {
|
||||
mid := (left + right) / 2
|
||||
|
||||
if arr[mid] == searchValue {
|
||||
fmt.Println("Found at position: ", mid)
|
||||
return
|
||||
} else if arr[mid] < searchValue {
|
||||
left = mid + 1
|
||||
} else {
|
||||
right = mid - 1
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Not found")
|
||||
}
|
Loading…
Reference in New Issue
Block a user