Skip to content

Instantly share code, notes, and snippets.

@Ignavia-Snippets
Last active January 1, 2016 22:18
Show Gist options
  • Save Ignavia-Snippets/8208762 to your computer and use it in GitHub Desktop.
Save Ignavia-Snippets/8208762 to your computer and use it in GitHub Desktop.
C: Searching
#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;
}
#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