Skip to content

Instantly share code, notes, and snippets.

@ehudthelefthand
Created June 18, 2017 06:36
Show Gist options
  • Save ehudthelefthand/37c86adcc174fc39dd2b7dca5cc5f869 to your computer and use it in GitHub Desktop.
Save ehudthelefthand/37c86adcc174fc39dd2b7dca5cc5f869 to your computer and use it in GitHub Desktop.
Simple Binary Search
#include <stdio.h>
#include <stdlib.h>
// or int *a
int binary_search(int a[], int x, int left, int right) {
if (left > right) return -1;
int mid = (left + right) / 2;
if (a[mid] == x) return mid;
if (x < a[mid]) return search(a, x, left, mid - 1);
else return search(a, x, mid + 1, right);
}
char **search(int a[], int x, int left, int right) {
int result = binary_search(a, x, left, right);
return result == -1 ? "Not Found :(" : "Found :D";
}
int main() {
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Search for %d: %s \n", 10, search(a, 10, 0, n - 1));
printf("Search for %d: %s \n", 20, search(a, 20, 0, n - 1));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment