Full width home advertisement

HTML

Tech News

Ad

  1. #include<stdio.h>
  2. //global declaractions
  3. int a[5],n=5,i;
  4.  
  5.  
  6. void ArrIn();
  7. void Binary();
  8. int main(){
  9.  
  10. ArrIn();
  11.  
  12.  
  13. Binary();
  14.  
  15. return 0;
  16. }
  17. void ArrIn(void){
  18. for(i=0;i<n;i++){
  19. printf("\nEnter %d element ",i+1);
  20. scanf("%d",&a[i]);
  21. }
  22. }
  23. void Binary(){
  24. int lb=1,ub=n,mid,find;
  25. printf("\n Enter element which you want to find");
  26. scanf("%d",&find);
  27.  
  28. while(lb<=ub){
  29. mid=(lb+ub)/2;
  30. if(find<mid){
  31. ub=mid-1;
  32. }
  33. else if(find>mid){
  34. lb=mid+1;
  35. }
  36. else if(find==mid){
  37. printf("\nElement found");
  38. break;
  39. }
  40.  
  41. }
  42. if(find!=mid){
  43. printf("\nElement not found");
  44. }
  45. }
  46.  

ALGORITHM

STEP 1:
    Read shorted a[n]
    initialize lb<-1,ub<-n
STEP 2:
    Repeat while lb<=ub
        mid<-(lb+ub)/2
          if(x<mid)
            then
                ub<-mid-1
           else if(x->mid)
             then
                lb<-mid+1
            else
                write "yes" or return mid
           end if
        end else if
    end while

STEP 3:

Write a[n]

Output

Binary search in c




No comments:

Post a Comment

Bottom Ad [Post Page]