AliAbdulKareem

binary_search.c

Sep 20th, 2021
1,346
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. static int binary_search(int* arr, int arr_size, int item)
  5. {
  6.     int low = 0;
  7.     int high = arr_size-1;
  8.        
  9.    
  10.    
  11.     while(low<=high)
  12.     {
  13.         int mid =(low + high/2);
  14.         int elem = arr[mid];
  15.         if(elem == item)
  16.         {
  17.             return (int)mid;
  18.         }
  19.         else if(elem < item)
  20.         {
  21.             low = mid +1;
  22.             printf("low = mid + 1 == %d\n",low);
  23.         }
  24.         else
  25.         {
  26.             high = mid -1;
  27.             printf("high = %d",high);
  28.             printf("  mid = %d , low = %d \n",mid,low);
  29.         }
  30.        
  31.     }
  32.     return -1; //indicating I reached the end without finding the number;
  33. }
  34. int main()
  35.  
  36. {
  37.     int a[11] = {1,3,6,7,8,14,16,18,20,31,50};
  38.         int index = binary_search(a,11,18);
  39.  
  40.             if(index == -1)
  41.             {
  42.                     printf("element wasn't found\n");
  43.             }
  44.             else
  45.             {
  46.                 printf("element was found at index %d\n",index);
  47.                
  48.             }
  49.  
  50.    
  51.    
  52. }
  53.  
RAW Paste Data