Binary search

Program to perform binary operation using linked list.. a simple method!

#include"stdio.h"
#include"conio.h"
#include"alloc.h"
struct node
{
int info;
struct node *next;
};
typedef struct node *nodeptr;
nodeptr getnode()
{
nodeptr p;
p=(nodeptr)malloc(sizeof(struct node));
p->next=NULL;
return p;
}
void freenode(nodeptr p)
{
free(p);
}
main()
{
int i,n,l,h,mid,ele,flag=0,pos;
nodeptr p,q,list;
clrscr();
printf("\nEnter the no of nodes : ");scanf("%d",&n);
printf("\nEnter the elements");
p=getnode();
printf("\nEnter info : ");scanf("%d",&p->info);
list=p;
for(i=1;i 'lesser than' n;i++) /* Replace lesser than with symbols*/
{
q=getnode();
printf("\nEnter info : ");scanf("%d",&q->info);
p->next=q;
p=q;
}
q->next=NULL;
printf("\nEnter the element to be searched : ");scanf("%d",&ele);
l=1;
h=n;
while(l<=h)
{
mid=(l+h)/2;
p=list;
for(i=1;i
p=p->next;
if(p->info==ele)
{
pos=mid;
flag=1;
break;
}
else if(p->info
l=mid+1;
else
h=mid-1;
}
if(flag)
printf("\n%d found in the list @ position %d",ele,pos);
else
printf("\nSearch unsuccessful!! Element not found in the list");
getch();
return 0;
}
Category: ,

0 comments: