C Program to Search a Given Number Using Binary Search


Couch ModePrint

PROGRAM:

#include<stdio.h>
main()
{
 int A[20],n,i,j,temp;
 clrscr();
 printf("Enter the size of array:\n");
 scanf("%d",&n);
 printf("Enter the array elements:\n");
 for(i=0;i<n;i++)
 scanf("%d",&A[i]);
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
   {
          if(A[j]>A[j+1])
           {
            temp=A[j];
            A[j]=A[j+1];
            A[j+1]=temp;
           }
   }
 }
 printf("The sorted arrays are as follows:\n");
 for(i=0;i<n;i++)
 printf("%d\t",A[i]);
 printf("enter the key element to search")
 scanf("%d",&key);
   min=0;
   max=n-1;
   while(min<=max)
          {
           mid=(int)((min+max)/2);
           if(key==A[mid])
          {
           printf("key is found in location %d",mid+1);
             break;
            }
           else if(key>A[mid])
           min=mid+1;
           else
           max=mid-1;
          }
   if(min>max)
   printf("Key not found");
  getch();
}

OUTPUT:

Enter the size of array:
6
Enter the array elements:
22
11
66
99
88
77
The sorted arrays are as follows:
11      22      66      77      88      99
 ENTER THE KEY ELEMENTS TO SEARCH 88
key is found in location 5

Enter the size of array:
6
Enter the array elements:
22
55
66
33
69
99
The sorted arrays are as follows:
22      33      55      69      99      66
 ENTER THE KEY ELEMENTS TO SEARCH 10
Key not found


Thank Your Valuable Comment Tool to Insert codes in Comments : Convert My Code. Hide

Select to parse the code (not required if code is already parsed):

Subscribe By Email

Join Our Newsletter

Get All The Latest Updates Delivered Straight Into Your Inbox For Free!

We Respect Your Privacy

Popular Posts