Friday 5 December 2014

C Program for Binary Search Algorithm

Program:

#include<stdio.h>
#include<conio.h>
void main( )
{
    int a[20],val,i,n,low,high,mid;
    clrscr( );
    printf("\nEnter the Number of Elements:");
    scanf("%d",&n);
    printf("\nEnter the %d of elements:",n);
    for(i=0;i<n;i++)
    {
    scanf("%d",&a[i]);
    }
    printf("\nThe Elements in the array are :");
    for(i=0;i<n;i++)
    {
    printf("\n%d",a[i]);
    }
    low=0;
    high=n-1;
    printf("\nEnter the Search Element:");
    scanf("%d",&val);
    while(low<=high)
   {
  mid=(low+high)/2;
  if(a[mid]==val)
  {
   printf("\nElement found");
   break;
  }
  else if(a[mid]>val)
  {
   low=mid-1;
  }
  else if(a[mid]<val)
  {
   low=mid+1;
  }
  else
  {
   printf("\nElement not found");
  }
    }
    if(low>high)
    {
    printf("\nElement not found");
    }
}


Output:

Enter the Number of Elements:5

Enter the 5 of elements:1
2
3
4
5

The Elements in the array are :
1
2
3
4
5

Enter the Search Element:5

Element found




0 comments:

Post a Comment