Skip to content

Instantly share code, notes, and snippets.

@monovertex
Created June 11, 2012 10:38
Show Gist options
  • Save monovertex/2909503 to your computer and use it in GitHub Desktop.
Save monovertex/2909503 to your computer and use it in GitHub Desktop.
A simple binary search example.
#include <stdio.h>
int* binary_search(int* v, int n, int x){
int m = n/2;
if(x == *(v+m))
return v;
else if(n == 1)
return NULL;
else if(x < *(v+m))
return binary_search(v, m, x);
else
return binary_search(v+m, n-m, x);
}
int main() {
int vector[10] = {2, 5, 7, 8, 10, 11, 100};
// should be ordered!
int size = 7, i;
int* found;
int search;
printf("The vector is:\n");
for(i = 0; i < size; i++){
printf("%i ", vector[i]);
}
printf("\nWhich is the value you wish to search for?\n");
while(1){
if(scanf("%i", &search) < 1) break;
found = binary_search(vector, 7, search);
if(found != NULL)
printf("Value found!\n");
else printf("Value is not in the vector!\n");
}
return 0;
}
@taygun
Copy link

taygun commented Jun 11, 2012

Looks good , i can't find something to disturb me.

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