Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




Search - Binary Search

/*******************************************/
/*PROGRAM TO PERFORM BINARY SEARCH*/
/*******************************************/

#include<stdio.h>
#include<conio.h>
void main()
{
       int a[10],n,i,j,temp,item,loc,mid,beg,end;
       clrscr();
       printf("Enter the size of array: ");
       scanf("%d",&n);
       printf("\nEnter the elements of array:\n");
       for(i=0;i<n;i++)
       {
              scanf("%d",&a[i]);
       }
       for(i=0;i<n-1;i++)
       {
              for(j=0;j<n-i;j++)
              {
                     if(a[j]>a[j+1])
                     {
                              temp=a[j];
                              a[j]=a[j+1];
                              a[j+1]=temp;
                     }
              }
       }
       printf("\nEnter the item tobe searched: ");
       scanf("%d",&item);
       beg=0;
       end=n-1;
       mid=(beg+end)/2;
       while((beg<=end)&&(a[mid]!=item))
       {
              if(item<a[mid])
              {
                     end=mid-1;
              }
              else
              {
                     beg=mid+1;
              }
              mid=(beg+end)/2;
       }
       printf("\nThe elements of array are:\n");
       for(i=0;i<n;i++)
       {
              printf("%d ",a[i]);
       }
       if(a[mid]==item)
       {
              loc=mid;
              printf("\nItem %d is present at %d location in the array",item,loc+1);
       }
       else
       {
              printf("\nItem %d is not present in the array",item);
       }
       getch();
}

Share this article   |    Print    |    Article read by 1465 times
Author:
Rohit kakria
I am software developer, moderator of xpode.com
Related Articles:
Related Interview Questions: No related interview question