Created
June 30, 2012 18:59
-
-
Save obstschale/3025110 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 binarySearch(char *list[ ], char target[ ], int n) | |
{ | |
int start, end, middle; | |
start = 0; | |
end = n - 1; | |
while (start <= end) | |
{ | |
middle = (start + end) / 2; | |
if (strcmp(target, list[middle]) < 0) | |
{ | |
end = middle - 1; | |
} | |
else | |
if (strcmp(target, list[middle) > 0) | |
{ | |
start = middle + 1; | |
} | |
else | |
{ | |
return middle; | |
} | |
} // end while | |
return -1; | |
} // end binary search |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Binary search is much faster than linear search.
For an ordered list of N entries, linear search requires a maximum of N array accesses, and binary search requires a maximum of log2 N (rounded up).