Created
February 5, 2014 00:46
-
-
Save kotaroito/8815418 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdlib.h> | |
| #include <stdio.h> | |
| #include <time.h> | |
| #define NOT_FOUND (-1) | |
| #define N (10) | |
| int binary_search(int x, int *a, int left, int right) | |
| { | |
| int mid; | |
| while ( left < right ) { | |
| mid = (left + right) / 2; | |
| if (a[mid] < x) | |
| left = mid + 1; | |
| else | |
| right = mid; | |
| } | |
| if ( a[left] ==x ) | |
| return left; | |
| return NOT_FOUND; | |
| } | |
| int main(void) | |
| { | |
| int i, found; | |
| int array[N]; | |
| srand((unsigned int) time(NULL)); | |
| array[0] = rand() % 3; | |
| for ( i = 1; i < N; i++ ) { | |
| array[i] = array[i - 1] + rand() % 3; | |
| } | |
| for (i = 0; i < N; i++ ) { | |
| printf("%d ", array[i]); | |
| } | |
| scanf("%d", &i); | |
| found = binary_search(i, array, 0, N); | |
| if ( found > -1 ) | |
| printf("index: %d\n", found); | |
| return EXIT_SUCCESS; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment