【问题标题】:Creating a new array from a slice of another in C在C中从另一个切片创建一个新数组
【发布时间】:2014-04-16 22:30:08
【问题描述】:

我是编程新手,我正在学习 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 
       }

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

【问题讨论】:

  • 那么问题是什么?
  • 我可以实现吗? new_array[] = values[0:middle_index] 不使用循环?
  • 只在同一个阵列上工作会获得更好的性能。拆分数组时,只需将数组变量以及要处理的范围的开始和结束索引传递给递归函数。无需复制数组或其任何子集。

标签: c arrays search binary


【解决方案1】:

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

bool search(int value, int values[], int low, int high)

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

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

你可以浏览网络,你会得到使用这种方法的二进制搜索实现,因为它是实现二进制搜索的常用方法。

【讨论】:

  • 你可以这样做,但它涉及的界面更改实际上是不必要的。
【解决方案2】:

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

if (middle_number > value)
    return search(value, array + middle_index, n - middle_index);

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

合理的调整(因为你知道array[middle_index] != value):

if (middle_number > value)
    return search(value, array + middle_index + 1, n - middle_index - 1);

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 2014-09-12
    • 2017-05-16
    • 2017-05-06
    • 2013-08-21
    • 1970-01-01
    • 2012-09-17
    • 2021-10-16
    相关资源
    最近更新 更多