feat: enhance recursive binary search to correctly return found index (#298)
Co-authored-by: armin <armin.eyvazi@snappshop.ir>
This commit is contained in:
@@ -19,7 +19,26 @@ func checkBin(list []int, i int) int {
|
|||||||
return -1
|
return -1
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func RecursiveCheckBin(list []int, item int, high, low int) int {
|
||||||
fmt.Println(checkBin([]int{1, 2, 3, 4, 5}, 1)) // 0
|
if high >= low {
|
||||||
fmt.Println(checkBin([]int{1, 2, 3, 4, 5}, -1)) // -1
|
mid := (high + low) / 2
|
||||||
|
|
||||||
|
if list[mid] == item {
|
||||||
|
return mid
|
||||||
|
} else if list[mid] > item {
|
||||||
|
return RecursiveCheckBin(list, item, mid-1, low)
|
||||||
|
} else {
|
||||||
|
return RecursiveCheckBin(list, item, high, mid+1)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user