Write a C program for binary search in ascending order to implement the arrays and functions.

#include<stdio.h>
#include<conio.h>
int BINARY_SEARCH(int arr[],int len,int item)
{
int top,bottom,mid;
top=0;
bottom=len-1;
mid=(top+bottom)/2;
do
{
            if(arr[mid]<item)
            {
                        top=mid+1;
                        mid=(top+bottom)/2;
            }
            else if(arr[mid]==item)
            {
                        return (mid);
                        break;
            }
            else if(arr[mid]>item)
            {
                        bottom=mid-1;
                        mid=(top+bottom)/2;
            }
}while(top<=bottom);

if(top>bottom)
{
            return (-1);
}
}
void main()
{
int a[10],ele,n,i,pos;
clrscr();
printf("\nENTER THE TOTAL ELEMENTS ");    scanf("%d",&n);
printf("ENTER ARRAY ");
for(i=0;i<n;i++)            {           scanf("%d",&a[i]);       }
printf("ENTER THE ELEMENT YOU WANT TO SEARCH "); scanf("%d",&ele);
pos=BINARY_SEARCH(a,n,ele);
if(pos!=-1)
{
printf("POSITION %d",pos);
}
else
{
printf("ELEMENT NOT PRESENT");
}
getch();
}


0 Comment "Write a C program for binary search in ascending order to implement the arrays and functions."

Post a Comment