Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change '01_introduction_to_algorithms/Golang/BinarySearch.go' #303

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 28 additions & 16 deletions 01_introduction_to_algorithms/Golang/BinarySearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,55 @@ package main

import "fmt"

func checkBin(list []int, i int) int {
func checkBin(list []int, i int) interface{} {
// low and high keep track of which part of the list you'll search in.
low := 0
high := len(list) - 1
// While you haven't narrowed it down to one element ...
for low <= high {
// ... check the middle element
mid := (low + high) / 2
// Found the item.
if list[mid] == i {
return mid
}
if list[mid] < i {
low = mid + 1
} else {
// The guess was too high.
if list[mid] > i {
high = mid - 1
// The guess was too low.
} else {
low = mid + 1
}
}
return -1
// Item doesn't exist
return nil
}

func RecursiveCheckBin(list []int, item int, high, low int) int {
func recursiveCheckBin(list []int, item int, high, low int) interface{} {
// Check base case
if high >= low {
mid := (high + low) / 2

// If element is present at the middle itself
if list[mid] == item {
return mid
// If element is smaller than mid, then it can only
// be present in left subarray
} else if list[mid] > item {
return RecursiveCheckBin(list, item, mid-1, low)
return recursiveCheckBin(list, item, mid - 1, low)
// Else the element can only be present in right subarray
} else {
return RecursiveCheckBin(list, item, high, mid+1)
return recursiveCheckBin(list, item, high, mid + 1)
}

}
return -1
// Element is not present in the array
return nil
}

// you can run this code on: https://go.dev/play/
func main() {
list := []int{1, 2, 3, 4, 5}
fmt.Println(checkBin(list, 2)) // 0
fmt.Println(checkBin(list, -1)) // -1
fmt.Println(RecursiveCheckBin([]int{1, 2, 3, 4, 5}, 2, len(list)-1, 0)) // 1
fmt.Println(RecursiveCheckBin([]int{1, 2, 3, 4, 5}, 0, len(list)-1, 0)) //-1
list := []int{1, 3, 5, 7, 9}
fmt.Println(checkBin(list, 3)) // => 1
fmt.Println(checkBin(list, -1)) // => <nil>
fmt.Println(recursiveCheckBin(list, 3, len(list)-1, 0)) // => 1
fmt.Println(recursiveCheckBin(list, -1, len(list)-1, 0)) // => <nil>
}