【问题标题】:Binary Search with strings in C在 C 中使用字符串进行二进制搜索
【发布时间】:2021-04-15 15:40:41
【问题描述】:

我已经实现了这种二进制搜索算法,目的是找到包含在数组中的所需字符。考虑到 ASCII 表,我尝试以标准方式进行 'if' 'else' 比较:[ if ( searchElement > arrayChar[mid] ... etc ]。这似乎不起作用,所以我意识到也许它与字符串比较有关。我现在使用函数 strcmp 并使用它的返回值进行比较:

(如果 string1 负值。如果 string1 > string2 -> 正值。如果 string1 == string2 -> 0。)

它似乎也不能正常工作。

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>

int binarySearch(int arraySize, char arrayChar[]) {
    
    // Variable declaration;
    char searchElement[2];
    int startingPoint = 0, endingPoint = arraySize - 1;
    
    // Input for desired search element;
    printf("\nSearch for: ");
    scanf(" %c", &searchElement);
    
    while (startingPoint <= endingPoint) {
        int mid = (startingPoint + endingPoint) / 2;
        if (strcmp(searchElement, arrayChar[mid]) == 0) {
            return mid;
        }
        else if (strcmp(searchElement, arrayChar[mid]) < 0)
            endingPoint = mid - 1;
        else {
            if (strcmp(searchElement, arrayChar[mid]) > 0)
                startingPoint = mid + 1;
        }
    }
    return -1;
}


int main() {
        
    // Array declaration;
    char randomCharArray[7] = {'a', 'c', 'e', 'f', 'f', 'g', 'h'};
    
    
    // Calling  binarySearch() ;
    if (binarySearch(6, randomCharArray) == -1) printf("Element not found!");
    else printf("Element found in [%d] .", binarySearch(6, randomCharArray));

    return 1;
    
}

【问题讨论】:

  • 使用%c 阅读并不能确保searchElement[1] == '\0'。字符串比较依赖于以空字符结尾的字符串。但是由于您将arrayChar[mid] 传递给strcmp(),因此您传递的是一个字符,而不是一个字符串。事实上,您应该将调用 strcmp() 替换为 if (searchElement == arrayChar[mid]) 等,因为您正在比较单个字符,而不是字符串。

标签: c string search binary char


【解决方案1】:

您似乎在区分单个 char 值和字符串时遇到了问题,它们是 char 值的连续序列,以一个值为 0 结尾。可以将成对的单个 char 值与标准进行比较关系和相等测试运算符(&lt;&gt;==。)。字符串对可以通过strcmp() 函数进行比较。 个别chars 不能直接与字符串比较,反正你也没有字符串,因为binarySearch()searchElement 的内容和main() 的@ 的内容都没有987654332@ 以 null 结尾。

这导致我提出建议 1:将 searchElement 设为 char,而不是数组,因为您知道您只需要它来表示单个 char

char searchElement;

完成此操作后,您现在可以(建议 2)通过标准运算符将 searchElement 的值与 arrayChar 的元素进行比较,正如您所说的最初尝试做的那样。例如,

    // with 'searchElement' as a char, not a char[]:
    if (searchElement == arrayChar[mid]) {

或者,如果您将searchElement 保留为数组,则可以使用searchElement[0] 访问其第一个char 以进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2021-11-19
    • 2013-05-22
    相关资源
    最近更新 更多