Advertisement
Shailrshah

Binary Search

Nov 7th, 2013
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include <stdio.h>
  2. int binarySearch(int a[], int low, int mid, int high, int x){
  3.     while(low<=high){
  4.         mid = (low+high)/2;
  5.         if(a[mid] == x) return mid;
  6.         else if(a[mid] > x) high = mid-1;
  7.         else if(a[mid] < x) low = mid+1;
  8.     }
  9.     return -1;
  10. }
  11. int main(){
  12.     int a[10];
  13.     int n, x, result;
  14.     printf("How many numbers are to inserted?: ");
  15.     scanf("%d",&n);
  16.     printf("Enter %d numbers.\n", n);
  17.     for(int i = 0; i<n; i++) scanf("%d", &a[i]);
  18.     printf("position: ");
  19.     for(int i = 0; i<n; i++) printf("\t%d\t", i);
  20.     printf("\nnumber: ");
  21.     for(int i = 0; i<n; i++) printf("\t%d\t", a[i]);
  22.     printf("\nWhich number do you want to search for?: ");
  23.     scanf("%d",&x);
  24.     result = (binarySearch(a, 0,(0-n-1)/2, n-1, x));
  25.     if(result+1) printf("Element at position %d is %d.", result, x);
  26.     else printf("Not found.");
  27. }
  28. //Output:-
  29. // How many numbers are to inserted?: 5
  30. // Enter 5 numbers.
  31. // 1
  32. // 2
  33. // 3
  34. // 4
  35. // 5
  36. // position:       0               1               2               3               4
  37. // number:         1               2               3               4               5
  38. // Which number do you want to search for?: 1
  39. // Element at position 0 is 1.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement