tampurus

1.2 Binary search

Dec 11th, 2021 (edited)
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.00 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. void Binary_Search(int arr[] , int find , int n){
  4.  
  5.     int low = 0 , high = n-1 , mid = (high + low) / 2, check=0;
  6.  
  7.     while(low<=high){
  8.  
  9.         if(arr[mid] == find){
  10.             check = 1;
  11.             break;
  12.         }
  13.         else if(find > arr[mid]){
  14.             low = mid + 1;
  15.         }
  16.         else{
  17.             high = mid - 1;
  18.         }
  19.         mid = (high + low) /2;
  20.     }
  21.    
  22.     if(check){
  23.         printf("Element %d found at %d position",find,mid+1);
  24.     }
  25.     else printf("Not found");
  26. }
  27. int main()
  28. {
  29.     int n,arr[100],find;
  30.     printf("Enter the number of element(upto 100) and elements with spaces\n");
  31.     scanf("%d",&n);
  32.     for(int i=0 ; i<n ; i++){
  33.         scanf("%d",&arr[i]);
  34.     }
  35.     printf("Enter the number you want to find ");
  36.     scanf("%d",&find);
  37.  
  38.     Binary_Search(arr,find,n);
  39. }
  40. /*
  41. Output->
  42. Enter the number of element(upto 100) and elements with spaces
  43. 3
  44. 1 2 3
  45. Enter the number you want to find 3
  46. Element 3 found at 3 position
  47. */
Add Comment
Please, Sign In to add comment