Hello guys and gals,
I made a simple Binary search tree and traversed it using intraversal so that the list gets sorted. Here is what I did.
Code:
#include<stdio.h>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 25
struct node
{
int info;
struct node *left;
struct node *right;
};
typedef struct node *vish;
vish tree,p,q;
vish maketree(int x)
{
p=malloc(sizeof(struct node));
p->info=x;
p->left=NULL;
p->right=NULL;
return p;
}
void setleft(vish p,int x)
{
if(p==NULL)
printf("void insertion\n");
else if(p->left!=NULL)
printf("invalid insertion\n");
else
p->left=maketree(x);
}
void setright(vish p,int x)
{
if(p==NULL)
printf("void insertion\n");
else if(p->right!=NULL)
printf("invalid insertion\n");
else
p->right=maketree(x);
}
void intrav(vish tree)
{
if(tree!=NULL)
{
intrav(tree->left);
printf("\n%d\n",tree->info);
intrav(tree->right);
}
}
int main(void)
{
int elt,i,x[MAX],y;
time_t first,second;
printf("Enter the number of elements in the tree\n");
scanf("%d",&elt);
printf("Enter elements one by one");
for(i=0;i<=elt-1;i++)
scanf("%d",&x[i]);
printf("The elements you entered are\n");
for(i=0;i<=elt-1;i++)
printf("%d\t",x[i]);
tree=maketree(x[0]);
for(i=1;i<elt;i++)
{
y=x[i];
q=tree;
p=q;
while(p!=NULL)
{
q=p;
if(y< p->info)
p=p->left;
else
p=p->right;
}
if(y<q->info)
setleft(q,y);
else
setright(q,y);
}
first=time(NULL);
intrav(tree);
second=time(NULL);
printf("\n\nTime taken to sort %f",difftime(second,first));
getch();
}
Now actually I want to look at the efficiency of the method, for that I used difftime function. But whatever number of elements I enter, the result is same 0.000000seconds. I was thinking of making the output something like MK27 has shown(elapsed time) in here(post no.14). How can I do that such that the time taken to sort the list is also displayed correctly in the output. I hope I made myself clear.
Thanks