Created
June 11, 2012 10:38
-
-
Save monovertex/2909503 to your computer and use it in GitHub Desktop.
A simple binary search example.
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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good , i can't find something to disturb me.