enh(Go): binary-search (#273)

pull/290/head
Atin Bainada 2021-05-08 22:38:04 +05:30 committed by GitHub
parent 5d0c19e8de
commit 4d4e3319b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 7 deletions

View File

@ -6,32 +6,39 @@ import (
"time" "time"
) )
func binarySearch(arr []int, elem int) { func binarySearch(arr []int, elem int) (int, bool) {
var ( var (
start = 0 start = 0
end = len(arr) - 1 end = len(arr) - 1
) )
fmt.Printf("Array: %v\nNumber to be searched: %v\n", arr, elem)
for start <= end { for start <= end {
mid := start + (end-start)/2 mid := start + (end-start)/2
if elem == arr[mid] { if elem == arr[mid] {
fmt.Printf("Number found at index %v", mid)
return return mid, true
} else if elem < arr[mid] { } else if elem < arr[mid] {
end = mid - 1 end = mid - 1
} else { } else {
start = mid + 1 start = mid + 1
} }
} }
return -1, false
fmt.Printf("Number not found!\n")
} }
func RunBinarySearch() { func RunBinarySearch() {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
arr := []int{1, 2, 4, 7, 8, 9, 12, 14, 17, 18, 20, 22, 23, 24, 26, 27, 29} arr := []int{1, 2, 4, 7, 8, 9, 12, 14, 17, 18, 20, 22, 23, 24, 26, 27, 29}
elem := rand.Intn(20) elem := rand.Intn(20)
binarySearch(arr, elem)
fmt.Printf("Array: %v\nNumber to be searched: %v\n", arr, elem)
index, found := binarySearch(arr, elem)
if !found {
fmt.Printf("Number not found!\n")
} else {
fmt.Printf("Number found at index %v", index)
}
} }