递归二进制搜索c

时间:2017-10-05 09:37:10

标签: c pointers recursion binary-search

// RecursiveBinarySearch.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#define N 9

int RecursiveBinarySearch(int A, int low, int high, int x);

int main()
{
    int A[N];
    int index = 0;
    //Put 
    A[0] = 2;
    A[1] = 6;
    A[2] = 13;
    A[3] = 21;
    A[4] = 36;
    A[5] = 47;
    A[6] = 63;
    A[7] = 81;
    A[8] = 97;

    printf("Elements in Array A\n");

    while (index <= 8) {
        printf("%d ", A[index]);
        index++;
    }

    printf("\nLocation(index) of element 63\n");

    printf("%d", RecursiveBinarySearch(A, 0, 8, 63));

    return 0;
}


int RecursiveBinarySearch(int A, int low, int high, int x) {

    //Base Condition
    if (low > high)
        return -1;

    int mid = low + (high - low) / 2;

    if (x == A[mid])
        return mid;
    else if (x < A[mid])
        return RecursiveBinarySearch(A, low, mid - 1, x);
    else
        return RecursiveBinarySearch(A, mid + 1, high, x);

}

这是第一个问题。 Visual Studio说 int A [9] 类型&#34; int *&#34;的参数与&#34; int&#34;

类型的参数不兼容

这是第二个问题。 中期 表达式必须具有指向对象类型的指针

我不太了解指针,所以我想知道为什么这段代码无法编译以及如何在此代码中使用指针。

2 个答案:

答案 0 :(得分:2)

最好完全删除所有分配A[0] = ..., A[1] = ...并写下:

int A[] = {2,6,13,21,36,47,63,81,97}

并替换

while (index <= 8)

由:

while (index < sizeof(A)/sizeof(A[0]))

sizeof(A) / sizeof(A[0])是数组A的元素数。 sizeof(A)是整个数组的大小(以字节为单位),sizeof(A[0])是数组中一个元素的大小(以字节为单位)。

但真正的问题在于:

替换:

int RecursiveBinarySearch(int A, int low, int high, int x)

通过

int RecursiveBinarySearch(int A[], int low, int high, int x)

但可能会有更多错误。

答案 1 :(得分:1)

严肃对待编译器警告:

helpPointer.c: In function ‘main’:
helpPointer.c:30:40: warning: passing argument 1 of ‘RecursiveBinarySearch’ makes integer from pointer without a cast [-Wint-conversion]
     printf("%d", RecursiveBinarySearch(A, 0, 8, 63));
                                        ^
helpPointer.c:4:5: note: expected ‘int’ but argument is of type ‘int *’
 int RecursiveBinarySearch(int A, int low, int high, int x);
     ^~~~~~~~~~~~~~~~~~~~~

正如评论中的人已经指出的那样,你将一个数组传递给递归二进制搜索方法,所以你应该像这样更改RecursiveBinarySearch

int RecursiveBinarySearch(int A[], int low, int high, int x);

int RecursiveBinarySearch(int *A, int low, int high, int x);

这是同一个东西,因为数组名称只是一个指向数组第一个元素的指针。如果您对阵列和指针之间的关系不太了解,请阅读this