c - 在 C 中进行二分查找时遇到问题

标签 c string binary-search

我在用 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);

        }
    }
}

二进制搜索是给我带来麻烦的功能。我没有收到任何段错误或任何东西,当我搜索文件中的名称时,什么也没有显示。这是我扫描到程序中的姓名列表。

  • 马特
  • 苏珊
  • 标记
  • 大卫
  • 亚丁
  • 菲尔
  • 埃里克
  • 约翰
  • 节奏
  • 我的

最佳答案

您的输入列表未排序,您的程序似乎也没有尝试对其进行排序。假设您要查找“susan” - 第一个比较是“susan”和“aden”,搜索区域缩小到最后 5 个项目,而“susan”在第二个位置......

关于c - 在 C 中进行二分查找时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24328657/

相关文章:

android - 带有字体标签的字符串资源不起作用

algorithm - 下界二进制搜索?

c - Code Jam 第 1A 轮 ProblemA 的 C++ 中的二分搜索

快速遍历大型二进制文件的算法

C - 动态矩阵分配 : something doesn't make sense to me

c - select() 系统调用未按预期工作

c - open失败,fopen不会

c - 打乱用户输入的字符串

PHP 相当于 Ruby 符号

R字符串拆分并压缩空白空间