以递归方式搜索未排序数组上的元素

时间:2016-07-11 11:52:48

标签: c arrays sorting search recursion

这是我参加考试的练习。它要求编写一个接收未排序数组v[]和数字X的函数,如果X中存在v[],则函数将返回1,如果{{1},则返回0在X中不存在。} 该函数必须递归,并且必须以这种方式工作:

v[]

所以我写了这个函数:

 1. Compares X with the element in the middle of v[];
 2. The function calls itself (recursion!!) on upper half and on the lower half of v[];

我试图在一张纸上模拟它并且似乎是正确的(即使我不确定)然后我将它写在ideone上它可以& #39;运行程序! 这是链接:https://ideone.com/ZwwpAW

我的代码实际上是错的(可能是!),还是与ideone相关的问题。有人能帮我吗?提前谢谢!!!

3 个答案:

答案 0 :(得分:2)

b=occ(p+pivot,dim-pivot,X);为0时,pivot出现问题,即当dim为1时。

下一个函数调用变为occ(p,1,X);这再次导致在连续循环中调用occ(p,1,X);

可以通过在呼叫中添加条件来修复它,如下面的代码所示。

int occ(int *p,int dim,int X){

  int pivot,a=0,b=0;
  pivot=(dim)/2;
  if(dim==0){
      return 0;
  }

  if(*(p+pivot)==X)
      return 1;

  if (pivot != 0)
  {
    a=occ(p,pivot,X);
    b=occ(p+pivot,dim-pivot,X);
  }

  if(a+b>=1)
      return 1;
  else{
      return 0;
  }
}

答案 1 :(得分:0)

实现导致堆栈溢出,因为如果输入只包含一个元素,则递归不会终止。这可以修复如下。

int occ(int *p, int dim, int X)
{
    int pivot, a, b;
        pivot = (dim) / 2;
    if (dim == 0)
    {
        return 0;
    }
    if (*(p + pivot) == X)
    {
        return 1;
    }

    if (dim == 1)
    {
        if (*(p + pivot) == X)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    a = occ(p,         pivot,       X);
    b = occ(p + pivot, dim - pivot, X);
    if (a + b >= 1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

答案 2 :(得分:0)

它应该只改变源代码中的这一行,以避免使用 occ(p,1,X)的无限循环:

   //if(dim==0) //end of array
   if (pivot == 0)
        return 0;