Thursday, November 17, 2011

Binary search in c with OUTPUT

    #include<conio.h>
       #include<stdio.h>
    
 
 void main()
  {
     int n[50],i,j,k,temp,first,mid,last,ser,flag=0;
     clrscr();
     printf("how many number u want to insert?");
     scanf("%d",&k);
     for(i=0;i<=k-1;i++){
          printf("Enter values?");
          scanf("%d",&n[i]);
    }
    for(i=0;i<=k-1;i++){

        for(j=i+1;j<=k-1;j++)
        {
          if(n[i]>n[j])
          {
            temp=n[i];
            n[i]=n[j];
            n[j]=temp;
         }
      }
   }
  
    printf("Sorting\n");

    for(i=0;i<=k-1;i++){

        printf("%d\n",n[i]);
    }  
   
    printf("Enter serching number?");
    scanf("%d",&ser);
    first=0;
    last=k-1;
    mid=(first+last)/2;
    while(last>=first)
    {
      if(ser==n[mid])
      {
         flag=1;
         break;
       }
       else if(n[mid]>ser)
        {
           first=first;
           last=mid-1;
           mid=(first+last)/2;
         }
        else if(n[mid]<ser)
         {
            first=mid+1;
            last=last;
            mid=(first+last)/2;
         }

    }
    if(flag==1){
   
         printf("\n");
         printf("SEARCHING NUMBER IS FOUND");
         printf("\n");
         printf(" POSITION OF SEARCHED NUMBER %d",mid+1);
    }
    else{
   
      printf("Searching Number not found");
    }
    getch();
 }




OUTPUT :
How many numbers u want to insert ? 5
Enter values ?22
Enter values ?34
Enter values ?6
Enter values ?78
Enter values ?44
Sorting :
6
22
34
44
78





No comments:

Post a Comment