二进制搜索不返回位置

问题描述 投票:0回答:1

此代码用于创建由10个随机整数填充的数组。它对数组进行排序,然后将其输入到二进制搜索函数中。我找不到搜索键所在的位置。

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


int binary_search(int array[], int search, int strt, int ending){
    int middle;

    middle = (strt + ending)/2;         //splitting the array in half to compare the search key
    if (search > array[middle]){
        binary_search(array, search, middle + 1, ending);
    }else if(search == array[middle]){
        printf("Your search key is indicated in %d position the array Ferrari\n", middle + 1);
        return middle;
    }else{
        binary_search(array, search, strt, middle -1);
    }
    return -1;
}


int main(){
    srand(time(NULL));      //random number seed generator
    int Ferrari[10];
    int size = 10;
    int selection;
    int temporary = 0;      //I'm using this variable to store the value returned from linear_search()
    int start = 0;
    int end;
    int i;


    for(int i=0; i<10; i++){
        Ferrari[i] = rand() % 100 + 1;      //this is to generate a random number between 0 and 101
    }


    printf("\nThe array Ferrari consists of -> ");
    for(int i=0; i<10; i++){        //printing the initial array
        printf("%d, ", Ferrari[i]);
    }


    //SORTING-----------------------------------------------------------------------------

    for(int f = 0; f < (size - 1); f++){
        for(int kk = 0; kk < (size - 1 - f); kk++){
            if(Ferrari[kk] > Ferrari[kk +1]){
                int Te_mP;
                Te_mP = Ferrari[kk + 1];
                Ferrari[kk+1] = Ferrari[kk];
                Ferrari[kk] = Te_mP;
            }
        }
    }

    //-------------------------------------------------------------------------------


    printf("\n");
    printf("\nThe sorted array Ferrari consists of -> ");
    for(int i=0; i<10; i++){        //printing the array after it has been sorted
        printf("%d, ", Ferrari[i]);
    }


    start = 0;
    end = i -1;


    printf("\n\n");
    printf("Please enter a number to test if it is included in the array or not\n");        //this will be used to implement the searching algorithm
    scanf("%d", &selection);


    temporary = binary_search(Ferrari, selection, start, end);


    return 0;
}

我不断得到答案,搜索键位于法拉利阵列的0中。我该如何解决?

[请让我知道我在这儿做错了什么。非常感谢。

c arrays sorting search binary-search
1个回答
1
投票

查看此行

end = i - 1;

我在哪里初始化?在您的循环中,您有

for(int i=0........

注意,输入int i=0表示您正在for块中创建一个新变量i。因此,这不会更改在顶部声明的原始i变量。尝试使用end = 9,或者为此目的最好定义一个常数。

#define ARR_SIZE 10

循环中

for(i=0; i<ARR_SIZE;i++)

然后初始化end = ARR_SIZE -1;

还有binary_search函数的另一件事是,当键不存在于数组中时,您将无法处理这种情况。有点像

if(end==start && array[end] != search)
    return -1;

这会检查搜索空间中只有一个元素而不是您的搜索元素,这意味着它不存在,因此我们返回-1。希望对您有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.