二进制搜索结果非常不一致

Binary Search Results being very inconsistent

在学校做编码练习,我们必须使用二进制搜索来查找数组中值的位置。输出应生成索引位置。

测试它时,它非常“碰运气”。有时它会说什么时候有一个值,而其他时候当一个值明显存在时它会出现“元素不存在于数组中”。正在努力解决这种不一致的根源。

任何 help/tips/advice 将不胜感激。

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

#define SIZE 10

int binarySearch(int array[], int starting, int ending, int searchKey)
{

if (ending >= starting)
{       
        int mid = starting + (ending - starting)/2;
        if (array[mid] == searchKey) return mid;
        if (array[mid] > searchKey) return binarySearch(array, starting, mid-1, searchKey);
        return binarySearch(array, mid+1, ending, searchKey);
}
return -1;
}

int main(void)
{
    int array[10],i;
    int searchKey;

    srand(time(NULL));
    for (i=0; i<10; i++)
    array[i]=rand()%100;

    printf("Array before sorting \n");
    for (i=0; i<10; i++)
    printf("%d \n", array[i]);
   
    printf("Enter a number to search\n");
    scanf("%d", &searchKey);

    int result = binarySearch(array, 0, SIZE-1, searchKey);
    (result == -1)? 

    //Displaying the results to the user
    printf("Element is not present in array")
    : printf("Element is present at index %d", result+1);
    
    return 0;
}

在应用二进制搜索之前,您的数组需要按 increasing/decreasing 顺序排序。

二分查找需要对数组进行排序。

参见例如https://en.wikipedia.org/wiki/Binary_search_algorithm#:~:text=Binary%20search%20works%20on%20sorted,lower%20half%20of%20the%20array.

它说:

In computer science, binary search, also known as ...., is a search algorithm that finds the position of a target value within a sorted array.

您可以通过以下方式生成数组:

for (i=0; i<10; i++)
    array[i]=rand()%100;

所以它显然不是一个排序数组。因此,二进制搜索将 工作。

您可以在数组上使用 qsort 对其进行排序。如果您不允许更改数组,您将需要除二进制搜索之外的另一种搜索算法。