值以两种不同的方式在升序数组中搜索

时间:2017-03-26 06:30:02

标签: c arrays function pointers

我正在为我的C类做一个项目。我们将在具有10个不同数字的升序数组中找到该值,然后搜索用户想要的值并返回搜索数字的索引。第一种方法称为线性搜索,它将数组中的每个元素与用户想要的值进行比较。第二种方法称为二进制,您可以将中间索引与搜索值进行比较。如果List [middle] = target element,则返回变量middle,它是元素的索引。如果目标元素大于List [Middle],则继续对阵列的右半部分进行处理。如果它较小,则在数组的左半部分继续相同的过程。只有在“Left”索引变量小于或等于“Right”索引变量之前,才会进行减半过程。如果找不到目标元素,则返回-1。

#include<stdio.h>
int main()
{
    int array[10];
    int i = 0,value;
    printf("Please enter 10 distinctive postive numbers with ascending             order.");
    for(i;i<10;i++)
    {
        scanf("%d",&array[i]);
    }
    printf("What value are you seaching for?");
    scanf("%d",value);
    printf("searchLinear(value,*array[10],10)");

    return 0;   
}

int searchLinear(int s,int *list[10],int n){
    list[n];
    int i = 0;
    for(i;i<n;i++)
    {
        if(s == *list[i])
            return *list[i];
    }
    if(i = n)
        return -1;
}   
int searchBinary(int s, int *list[10],int n) {
    list[n];
    int i,left,right,middle;
    left = 0;
    right = n-1;

    for(i = 0;i<n/2;i++)
    {
        middle = (left + right)/2;

        if(*list[middle] > s)   
            right = middle;
        else if(*list[middle] < s)
            left = middle;
        else if(*list[middle] = s)
            return *list[middle];

        if(left == right)
            return -1;  
    }
}

这是我的代码,看起来像是无限循环。我该如何解决?

1 个答案:

答案 0 :(得分:0)

更正后的代码为

   #include<stdio.h>
    int searchLinear(int s,int list[],int n);
    int searchBinary(int s, int list[],int n);   //you need to give forward declaration of funcs

int main()
    {
        int array[10];
        int i = 0,value;
        printf("Please enter 10 distinctive postive numbers with ascending       order.");
        for(i;i<10;i++)
        {
            scanf("%d",&array[i]);
        }
        printf("What value are you seaching for?");
        scanf("%d",&value);        //you missed & here
        printf("%d",searchBinary(value,array,10));

        return 0;   
    }

    int searchLinear(int s,int list[],int n){      // you can use this format of arguments
        //list[n];        //what did you wanted to do with this line
        int i = 0;
        for(i;i<n;i++)
        {
            if(s == list[i])
                return i;             //return index not value
        }
        if(i = n)
            return -1;
    }   
     int searchBinary(int s, int list[],int n){
        //list[n];
        int i,left,right,middle;
        left = 0;
        right = n-1;

        for(i = 0;i<n/2;i++)
        {
            middle = (left + right)/2;
             if(left > right)      //you have to check left>right, instead of left==right
                return -1;  
            if(list[middle] > s)   
                right = middle-1;
            else if(list[middle] < s)
                left = middle+1;
            else if(list[middle] == s)    //== is used for comparision
                return middle;

        }
    }

观察评论中的更正