Last active
January 1, 2016 22:18
-
-
Save Ignavia-Snippets/8208762 to your computer and use it in GitHub Desktop.
C: Searching
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 "search.h" | |
int binary_search(int *a, int len, int x) { | |
int l = 0; | |
int r = len - 1; | |
while (l <= r) { | |
int m = l + (r - l) / 2; | |
if (a[m] == x) { | |
return m; | |
} else if (a[m] < x) { | |
l = m + 1; | |
} else { | |
r = m - 1; | |
} | |
} | |
return -1; | |
} | |
int linear_search(int *a, int len, int x) { | |
int i; | |
for (i = 0; i < len; i++) { | |
if (a[i] == x) { | |
return i; | |
} | |
} | |
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
#ifndef SEARCH | |
#define SEARCH | |
int binary_search(int *a, int len, int x); | |
int linear_search(int *a, int len, int x); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment