Binary Search Algorithm in C

Get Certified in C Programming and Take Your Skills to the Next Level

Program 1

// Program for Binary Search
#include<stdio.h>
#include<conio.h>
int main()
{
        int a[500],n,i,j,temp,s,low,high,mid,f=0;
        system("cls");
        xyz: printf("\nEnter the limit of array");
        scanf("%d",&n);
        if(n<0 || n>500)
       { 
          printf("\nInvalid limit please enter again)");
           goto xyz;
       }
       else
       {
           printf("\n Enter an element in array");
           for(i=0;i<n;i++)
             scanf("%d",&a[i]);
           // Sorting 
             for(i=0;i<n;i++)
             {
                  for(j=i+1;j<n;j++)
                  {
                      if(a[j]<a[i])
                      {
                           temp=a[i];
                           a[i]=a[j];
                           a[j]=temp;
                      }
                  }
             }
            //  printf("\n sorted elements ");
            //  for(i=0;i<n;i++)
            //    printf("\n %d",a[i]);  

            // Binary Search
           printf("\n Enter an element for search");
           scanf("%d",&s);
           low=0;
           high=n-1;
           while(low<=high)
           {
                 mid=(low+high)/2;
                 if(s==a[mid])
                 {
                      f=1;
                      break;
                 }
                 if(s>a[mid])
                       low=mid+1;
                 else
                    high=mid-1;      
           }
           if(f==1)
               printf("\n Searching success");
           else
              printf("\n Searching not success");   
   }
return 0;
}

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *