我在c中对字符串进行二进制搜索时遇到问题。我使用strcmp函数来比较字符串,但是当我输入我知道在列表中的名称时,我仍然没有输出。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 25
void insert_sata(char **strings, const char* filename, int size);
void allocate( char ***strings, int size);
int binary_search(char **strings, char *target, int start_idx, int end_idx);
int main(int argc, char* argv[]){
if(argc != 4){
printf("Wrong number of args");
}
char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
insert_data(pointer, argv[2], size);
int x;
int z = 1;
char search_name[MAX_STRING_LEN];
while( z == 1){
printf("\nEnter a name to search for: ");
scanf("%s", search_name);
x = binary_search(pointer, search_name, 0, size);
printf("\nContinue searching names? ( 1 = yes, 0 = No):");
scanf("%d", &z);
}
}
void allocate(char ***strings, int size){
int i;
*strings = malloc(sizeof(**strings) * size);
for( i = 0; i < size; i++)
{
(*strings)[i] = malloc(sizeof(char) * MAX_STRING_LEN);
}
}
void insert_data(char **strings, const char* filename, int size){
FILE *input;
input = fopen(filename, "r");
int i;
for (i = 0; i < size; i++){
fscanf(input,"%24s", strings[i]);
}
fclose(input);
}
int binary_search(char **strings, char *target, int start_idx, int end_idx){
int result;
int mid_idx = 0;
while( end_idx >= start_idx){
mid_idx = (end_idx + start_idx) / 2;
result = strcmp(strings[mid_idx], target);
if(result > 0){
end_idx = start_idx - 1;
}
else if (result < 0){
start_idx = mid_idx + 1;
}
else if( result == 0){
printf("%s was found in the set", target);
}
}
}
二进制搜索是给我带来麻烦的功能。我没有收到任何seg故障或任何东西,当我搜索文件中的名称时,没有显示任何内容。这是我扫描到程序中的名称列表。
答案 0 :(得分:3)
您的输入列表未排序,您的程序似乎没有尝试对其进行排序。假设你寻找苏珊&#39; - 第一个比较是&#39; susan&#39;到了&#39; aden&#39;,搜索范围缩小到最后5个项目,而&#39; susan&#39;处于第二位......
答案 1 :(得分:0)
这:
if (result > 0) {
end_idx = start_idx - 1;
}
可能意味着:
if (result > 0) {
end_idx = mid_idx - 1;
}
答案 2 :(得分:0)
binary search algorithm要求对列表进行排序。您的示例列表不是,因此算法将无效