Created
May 27, 2015 06:21
-
-
Save ikbear/3b15c218b5fa4ba014fc to your computer and use it in GitHub Desktop.
Binary Search in C
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
#include <stdio.h> | |
int binary_search(int *a, int length, int target) | |
{ | |
int left = 0; | |
int right = length - 1; | |
int middle = 0; | |
while (left <= right) | |
{ | |
middle = (left + right) >> 1; | |
if (a[middle] > target) | |
{ | |
right = middle - 1; | |
} | |
else if (a[middle] < target) | |
{ | |
left = middle + 1; | |
} | |
else | |
{ | |
return middle; | |
} | |
} | |
return -1; | |
} | |
int main() | |
{ | |
int a[5] = {2, 3, 4, 8, 10}; | |
int i = binary_search(a, 5, 8); | |
printf("%d\n", i); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment