New Android apps UniqueKey

Friday 20 February 2015

Binary search


#include<stdio.h>

main()
{

    int arr[100],i,n,key,c=0,first,last,mid;

    printf("Enter the number of element in array :   ");
    scanf("%d",&n);

    printf("Enter the elements in ascending order :   ");
    for(i=0;i<n;i++)
 {
         scanf("%d",&arr[i]);
    }

    printf("Enter the number to be search :   ");
    scanf("%d",&key);

    first=0;
 last=n-1;
    
    while(first<=last)
 {
         mid=(first+last)/2;
         
         if(key==arr[mid])
   {
             c=1;
             break;
         }
         else if(key<arr[mid]){
             last=mid-1;
         }
         else
             first=mid+1;
    }
    if(c==0)
         printf("The number is not found.");
    else
         printf("The number is found.");

    return 0;
}

No comments:

Post a Comment