Shakil_Hossain

binarySearch.c

Oct 22nd, 2020
659
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2.  
  3. int main(){
  4. int size;
  5. printf("Enter array size : \t");
  6. scanf("%d",&size);
  7. char arra[size];
  8. printf("\nEnter %d elements : \n",size);
  9.  
  10. for(int i=0;i<size;i++)
  11.     scanf("%s",&arra[i]);
  12. printf("\nThe elements are : \t");
  13. for(int i=0;i<size;i++)
  14. printf("%c\t",arra[i]);
  15.  
  16. char searchValue = 'a';
  17. int first,last,middle;
  18. first = 0;
  19. last = size - 1;
  20. middle = (first + last) / 2;
  21.  
  22. while(first <= last){
  23.     if(searchValue == arra[middle]){
  24.         printf("\nElement found in %d index",middle);
  25.         break;
  26.     }
  27.     else if(arra[middle] > searchValue)
  28.         last = middle - 1;
  29.     else
  30.         first = middle + 1;
  31.     middle = (first + last) / 2;
  32. }
  33. if(first > last)
  34.     printf("\nElement not found");
  35. return 0;
  36. }
  37.  
RAW Paste Data