From 4d4e3319b68b28481f70447d7ddf1456cfc3de31 Mon Sep 17 00:00:00 2001 From: Atin Bainada <61903527+atin@users.noreply.github.com> Date: Sat, 8 May 2021 22:38:04 +0530 Subject: [PATCH] enh(Go): binary-search (#273) --- algorithms/Go/searching/binary-search.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/algorithms/Go/searching/binary-search.go b/algorithms/Go/searching/binary-search.go index a3e2a99c..39d4efe2 100644 --- a/algorithms/Go/searching/binary-search.go +++ b/algorithms/Go/searching/binary-search.go @@ -6,32 +6,39 @@ import ( "time" ) -func binarySearch(arr []int, elem int) { +func binarySearch(arr []int, elem int) (int, bool) { var ( start = 0 end = len(arr) - 1 ) - fmt.Printf("Array: %v\nNumber to be searched: %v\n", arr, elem) - for start <= end { mid := start + (end-start)/2 if elem == arr[mid] { - fmt.Printf("Number found at index %v", mid) - return + + return mid, true } else if elem < arr[mid] { end = mid - 1 } else { start = mid + 1 } } + return -1, false - fmt.Printf("Number not found!\n") } func RunBinarySearch() { rand.Seed(time.Now().UnixNano()) arr := []int{1, 2, 4, 7, 8, 9, 12, 14, 17, 18, 20, 22, 23, 24, 26, 27, 29} 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) + } + } +