I wrote a code with function and using strcmp.I entered 5 names in the program (one of them is sara).and when i search for them i can find all of them but not sara. why when i search sara it can't be find?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fbubble(char [][21],int);
int fsearch(char [][21],char [],int);
int main(int argc, char *argv[]) {
const int n=5;
int i;
char name[21],a[n][21];
printf("enter 5 name\n");
for(i=0;i<n;i++)
gets(a[i]);
fbubble(a,n);
printf("enter name to search\n");
gets(name);
if(fsearch(a,name,n)==-1)
printf("name not exist in the table\n");
else printf("name exist in the table\n");
getch();
return 0;
}
//**********************************************
void fbubble(char a[5][21],int n){
int i,j;
char temp[21];
for(i=n-1;i>0;i--)
for(j=0;j<i;j++)
if(strcmp(a[j],a[j+1])>0){
strcpy(temp,a[j]);
strcpy(a[j],a[j+1]);
strcpy(a[j+1],temp);
}
}
//**********************************************
int fsearch(char a[5][21],char name[21],int n){
int mid,low=0,high=n-1;
while(low<high){
mid=(low+high)/2;
if(strcmp(name,a[mid])<0)
high=mid-1;
else if(strcmp(name,a[mid])>0)
low=mid+1;
else return mid;
}
return -1;
}
It's about your comparison of high and low
Let's think about this logically
We have
['ahmad','ali','masoud','reza','sara']
0 1 2 3 4
high = 4
, low = 0
, mid = 2
masoud != sara
low = mid+1 = 3
mid = 7/2 = 3
reza != sara
low = mid+1 = 4
high>low == false;break;
To Fix:
you want while(low<=high)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments