fork download
  1. #include <stdio.h>
  2. void main(){
  3. int i,n,key;
  4. printf("22A91A6151\n");
  5. printf("ENTER THE NUMBER OF ELEMENTS:");
  6. scanf("%d",&n);
  7. int a[n];
  8. printf("ENTER THE ELEMENTS:");
  9. for(i=0;i<n;i++){
  10. scanf("%d",&a[i]);
  11. }
  12. int low=0,high=n-1;
  13. printf("ENTER THE ELEMENT TO BE SEARCHED:");
  14. scanf("%d",&key);
  15. int flag=binarysearch(a,low,high,key);
  16. if(flag==-1)
  17. printf("Search Unsuccessful");
  18. else
  19. printf("Search Successful, Element found at position :%d",flag);
  20. }
  21. int binarysearch(int *a,int low,int high,int key){
  22. if(low==high)
  23. {
  24. if(a[low]==key)
  25. return low;
  26. else
  27. return -1;
  28.  
  29. }
  30. else
  31. {
  32. int mid=low+(high-low)/2;
  33. if(key==a[mid])
  34. return mid;
  35. else if(key>a[mid])
  36. return binarysearch(a,mid+1,high,key);
  37. else
  38. return binarysearch(a,low,mid-1,key);
  39. }
  40. }
  41.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
22A91A6151
ENTER THE NUMBER OF ELEMENTS:ENTER THE ELEMENTS:ENTER THE ELEMENT TO BE SEARCHED:Search Successful, Element found at position :0