Tuesday 17 March 2009

Binary Searh+sort+Seq sort

#include
#define size 10

void sort ( int[]);
void seqsearch (int[], int);
void binarysearch (int [], int);

void main ()
{
int list[] = {10,19,18,17,16,15,14,13,12,11};
int target;
int i;

printf("\nEnter the value to search : ");
scanf("%d",&target);

seqsearch(list,target);
sort (list);
binarysearch (list,target);

printf("\n\t\tSORTED LIST\n");
for (i=0; i printf("\nList[%d]= %d\n",i,list[i]);

}

void seqsearch(int list[], int t)
{
int i=0;

printf("\n\t\tSequential Search Technique\n");

while(i ++i;

if( i printf("\nTarget was found in location %d\n",i);
else
printf("\nTarget not in the list\n");

}

void sort(int list[])
{
int i,j,temp;

for(i=0; i for( j=i+1; j if(list[i]>list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}

void binarysearch(int list[],int t)
{
printf("\n\t\tBinary Search Technique\n");

int mid,first=0, last=size-1;

while(first {
mid=(first+last)/2;

if(t>list[mid])
first=mid+1;
else if(t last=mid-1;
else
break;
}

if(t==list[mid])

printf("\nTarget was found in location %d \n",mid);
else
printf("\nTarget not in the list\n");
}

1 comment:

Anonymous said...

Your code is messed up because your operators like "less-than" got interpreted as HTML and don't display.

But anyway, I looked at the source and your binary search is wrong.

For example, consider searching the 1-element list.
So first = 0, last = size-1 = 0. The while loop does not run because first is not less than last. Then in the "if" condition you try to access list[mid], except that the variable mid has NEVER BEEN INITIALIZED!!