Skip to content

Instantly share code, notes, and snippets.

@obstschale
Created June 30, 2012 18:59
Show Gist options
  • Save obstschale/3025110 to your computer and use it in GitHub Desktop.
Save obstschale/3025110 to your computer and use it in GitHub Desktop.
Binary Search
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
@obstschale
Copy link
Author

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment