Last active
March 20, 2021 13:42
-
-
Save dariodip/d54976e361fec510afe68a64cfa90e82 to your computer and use it in GitHub Desktop.
Binary Search
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
int bsa(int a[], int n, int t) { | |
int lft = 0, rgt = n - 1; | |
while (lft <= rgt) { | |
int m = (lft + rgt) / 2; | |
if (a[m] < t) { | |
lft = m + 1; | |
} else if (a[m] > t) { | |
rgt = m - 1; | |
} else { | |
return m; | |
} | |
} | |
return -1; | |
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
import math | |
func bsa(a []int, n int, t int) int { | |
lft := 0 | |
rgt := n - 1 | |
for lft <= rgt { | |
m := int(math.Floor(float64((lft + rgt) / 2))) | |
if a[m] < t { | |
lft = m + 1 | |
} else if a[m] > t { | |
rgt = m - 1 | |
} else { | |
return m | |
} | |
} | |
return -1 | |
} |
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
from math import floor | |
def bsa(a, n, t): | |
lft = 0 | |
rgt = n -1 | |
while lft <= rgt: | |
m = floor((lft + rgt) / 2) | |
if a[m] < t: | |
lft = m+1 | |
elif a[m] > t: | |
rgt = m-1 | |
else: | |
return m | |
return -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment