如何使用递归函数返回数组中整数的索引?

how can i return the index of an integer in an array using a recursive function?

本文关键字:整数 索引 数组 何使用 递归函数 返回      更新时间:2023-10-16

>我必须使用递归函数在数组中找到整数的索引,这就是我现在所拥有的:

#include <iostream>
int linear_search(int array[], int choice_, int size) {
if (array[choice_] >= 0) {
return array[choice_];
}
else {
return -1;
}
}

例如,如果:

int array[]= {3,4,7,8};

如果我输入我想搜索数字 3,它应该给我索引 0,但它给我数字 8。 我可以得到一些建议吗?

递归是关于将问题缩小到较小的问题。

在此特定搜索的情况下,请尝试将其视为找到的项目位于数组中的第一个位置,或者可能位于数组的其余部分。 这样就可以将问题减少到搜索较小的数组,直到找到该项目或遇到空数组的琐碎情况。

int linear_search(int array[], int choice_, int size)
{
// Array is empty -- not found
if (size <= 0)
return -1;
// Found at position 0
if (array[0] == choice_)
return 0;
// TODO: Search position in remaining array
int pos = linear_search(/* USE BRAIN HERE */);
// TODO: You may want to do something to the result before returning it
return pos;
}

如您所见,我留下了一些部分供您填写。 我对你有信心。 你可以的!

祝您编码愉快!

这是二叉搜索。它是一个递归函数。

int binary_search_recursive(const int b[], int search_key, int low, int high)  
{  
if (low > high)  
return -1;  
int mid = low + (high - low) / 2;  
if (search_key == b[mid])  
return mid;     
else if (search_key < b[mid])  
return binary_search_recursive(b, search_key, low, mid - 1);    
else  
return binary_search_recursive(b, search_key, mid + 1, high);  
} 

此代码错误

if (array[choice_] >= 0) {
return array[choice_];

当您执行array[choice_]时,您正在查看索引choice_处的数组值。这不是你想要的。相反,您想找出某个索引处的数组是否等于choice_。那将是if (array[some_index] == choice_) return some_index;

此外,要使其成为递归方法,函数需要调用自身。您的代码不会这样做,因此它不是递归的。

这是一种递归方法:

int searchArray(const int* array, const int choice_, const int size)
{
if (size > 0)
{
if (array[size-1] == choice_) return size-1;  // Hit! Return the index
return searchArray(array, choice_, size-1);   // Recursive call - pretend array is 1 shorter
}
return -1;
}

代码查看数组中的最后一个元素。

  • 如果是命中,它只是返回索引。

  • 如果它不是命中,它会调用自己,但递减size假装数组短一个元素。

这样,它从数组的末尾到数组的开头,同时寻找choice_

顺便说一句:请注意,对这个任务使用递归是一个非常糟糕的主意 - 永远不要这样做!使用简单的for循环。但我想这只是一个非常糟糕的家庭作业任务的另一个例子......