在C中从另一个数组的切片创建新数组

在C中从另一个数组的切片创建新数组,c,arrays,search,binary,C,Arrays,Search,Binary,我是编程新手,正在学习C语言。我试图用递归来解决一个问题。我已经找到了很多关于这方面的信息,我可以在我的程序中使用它,但我仍然想尝试一些不同的东西。我的问题如下:我有 bool search(int value, int values[], int n) // int value is value to search, // int values[] is the array in which value is to be found (or not) // int n is size of

我是编程新手,正在学习C语言。我试图用递归来解决一个问题。我已经找到了很多关于这方面的信息,我可以在我的程序中使用它,但我仍然想尝试一些不同的东西。我的问题如下:我有

bool search(int value, int values[], int n) 
// int value is value to search, 
// int values[] is the array in which value is to be found (or not)
// int n is size of array

// some code here and then:

       if (middle_number > value)
       {
           int new_array[] = values[0:middle_index];
           // I want my new array to be some slice of values[]
           // by declaring a range from 0 to the middle_index
           // Is that possible? 
           search(value, new_array, middle_index);
           // Using recursion 
       }

我可以循环创建新的数组,但是,我想,我会失去二进制搜索的优势(性能更好)

C语言不支持整数数组的直接数组切片功能。
要实现二进制搜索,可以传递数组索引以指示要使用的数组部分

bool search(int value, int values[], int low, int high)
其中,low是较低的索引,high是要在函数代码中使用的较高数组索引。您甚至可以创建int值[]作为全局变量,然后使用搜索函数作为

bool search(int value,int low, int high)

您可以浏览网络,您将使用此方法获得二进制搜索实现,因为它是实现二进制搜索的常用方法。

在C中,对于给定的问题,您使用指针算法完全绕过该问题(不需要数组的副本;只需在数组的有限部分中搜索,就像它是数组一部分的副本一样):

可能需要对参数列表(范围为±1)进行一些调整,但概念是将中间元素的地址和数组顶部的大小传递给递归调用

合理的调整(因为您知道
数组[中间索引]!=value
):


那么问题是什么?我可以实现吗?新的数组[]=值[0:中间的索引]不使用循环?只处理同一个数组可以获得更好的性能。分割数组时,只需将数组变量以及要处理的范围的开始和结束索引传递给递归函数。不需要复制数组或其任何子集。可以这样做,但它涉及一个i实际上不必要的界面更改。
if (middle_number > value)
    return search(value, array + middle_index, n - middle_index);
if (middle_number > value)
    return search(value, array + middle_index + 1, n - middle_index - 1);