Adding implementation of binary search rank
This commit is contained in:
parent
1ddd54676c
commit
b867cd616a
21
algs4/src/meatballhat.com/algs4/binarysearch.go
Normal file
21
algs4/src/meatballhat.com/algs4/binarysearch.go
Normal file
@ -0,0 +1,21 @@
|
||||
package algs4
|
||||
|
||||
func BinarySearchRank(key int, a []int) int {
|
||||
lo := 0
|
||||
hi := len(a) - 1
|
||||
|
||||
var mid int
|
||||
|
||||
for lo <= hi {
|
||||
mid = lo + (hi - lo) / 2
|
||||
if key < a[mid] {
|
||||
hi = mid - 1
|
||||
} else if key > a[mid] {
|
||||
lo = mid + 1
|
||||
} else {
|
||||
return mid
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
Loading…
Reference in New Issue
Block a user