Promi_38

binary search

Nov 19th, 2020 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. int Rbinary_search(int a[], int l, int r, int key)
  4. {
  5.     int found = 0, mid, i = 0;
  6.     while(l <= r)
  7.     {
  8.         mid = (l + r) / 2;
  9.         printf("Step %d: Left %d Mid %d Right %d\n        Mid Value: %d\n", i+1, l, mid, r, a[mid]);
  10.         if(key == a[mid])
  11.         {
  12.             printf("%d is found\n", key);
  13.             found = 1;
  14.             break;
  15.         }
  16.         else if(key > a[mid]) l = mid + 1; //idx = Rbinary_search(a, mid+1, r, key);
  17.         else r = mid - 1; //Rbinary_search(a, l, mid - 1, key);
  18.         i++;
  19.     }
  20.     if(found == 0) printf("%d is not found\n", key);
  21.     printf("Number of steps is %d\n", i+1);
  22.    
  23. }
  24.  
  25. int main()
  26. {
  27.     int n;
  28.     printf("Enter the size of the array: ", &n);
  29.     scanf("%d", &n);
  30.    
  31.     int a[n], i;
  32.     printf("Enter the elements: ");
  33.     for(i = 0; i < n; i++) scanf("%d", &a[i]);
  34.  
  35.     int key;
  36.     printf("Enter the value you want to search: ");
  37.     scanf("%d", &key);
  38.     printf("Find %d in the array:\n", key);
  39.  
  40.     Rbinary_search(a, 0, n, key);
  41.    
  42. }
  43.  
Add Comment
Please, Sign In to add comment