Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int binarySearch(int a[], int low, int mid, int high, int x){
- while(low<=high){
- mid = (low+high)/2;
- if(a[mid] == x) return mid;
- else if(a[mid] > x) high = mid-1;
- else if(a[mid] < x) low = mid+1;
- }
- return -1;
- }
- int main(){
- int a[10];
- int n, x, result;
- printf("How many numbers are to inserted?: ");
- scanf("%d",&n);
- printf("Enter %d numbers.\n", n);
- for(int i = 0; i<n; i++) scanf("%d", &a[i]);
- printf("position: ");
- for(int i = 0; i<n; i++) printf("\t%d\t", i);
- printf("\nnumber: ");
- for(int i = 0; i<n; i++) printf("\t%d\t", a[i]);
- printf("\nWhich number do you want to search for?: ");
- scanf("%d",&x);
- result = (binarySearch(a, 0,(0-n-1)/2, n-1, x));
- if(result+1) printf("Element at position %d is %d.", result, x);
- else printf("Not found.");
- }
- //Output:-
- // How many numbers are to inserted?: 5
- // Enter 5 numbers.
- // 1
- // 2
- // 3
- // 4
- // 5
- // position: 0 1 2 3 4
- // number: 1 2 3 4 5
- // Which number do you want to search for?: 1
- // Element at position 0 is 1.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement