-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding example to Golang sorted string binary serach
- 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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |