Skip to content

Commit

Permalink
Adding example to Golang sorted string binary serach
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashutosh Kumar Rai committed Feb 29, 2024
1 parent 059dda8 commit 71a3021
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions 01-sorted-string-slice-binary-search/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package main

import "fmt"

var counter int

func goBinarySearch(arr []string, target string) int {
low := 0 // 0
high := len(arr) - 1 // 6

for low <= high { // true
counter++
mid := low + (high-low)/2 // = 0 + 6 - 0 = 6 / 2 = 3

// fmt.Println(arr[mid] < target, target, arr[mid], mid, low, high)
if arr[mid] == target { // false
return mid
}

if arr[mid] < target { //
low = mid + 1
} else {
high = mid - 1
}
}

return -1
}

func main() {
// Example sorted slice of strings
sortedSlice := []string{"apple", "banana", "cherry", "grape", "orange", "pineapple", "strawberry"}
// Target string to search for
target := "orange"

// Perform binary search
index := goBinarySearch(sortedSlice, target)

// Display result
if index != -1 {
fmt.Printf("%s found at index %d\n", target, index)
fmt.Println("Max no of loop execution:", counter)
} else {
fmt.Printf("%s not found in the slice\n", target)
}
}

0 comments on commit 71a3021

Please sign in to comment.