如何使用递归函数返回数组中整数的索引?
how can i return the index of an integer in an array using a recursive function?
>我必须使用递归函数在数组中找到整数的索引,这就是我现在所拥有的:
#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
循环。但我想这只是一个非常糟糕的家庭作业任务的另一个例子......
相关文章:
- 跟随整数索引列表的自定义类迭代器
- 如果索引不是整数,我们如何在 C++ 中插入哈希表
- 如何更好地表示 6 个整数键而不是作为 6 维数组的索引?
- 如何使用递归函数返回数组中整数的索引?
- 我无法显示包含整数最大值的索引. 但我可以显示数组中整数的最高值
- 通过字符串的字符对整数数组进行索引
- 可以使用整数索引访问向量元素吗?
- 数组索引在地图上不是整数
- Char阵列中的特定索引的C 拉动签名整数
- 如何将整数存储在字符数组的单个索引中
- 阵列索引(转换为整数)用范围枚举
- SDL_JoystickName C++ 中的整数索引
- 将多个整数添加到一个向量索引? 'Cout'不起作用
- 在C++中为整数指针编制索引
- C++ 中 15000 数组索引之后的不相关整数标准输入
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- 如何使用模板创建排序映射整数索引
- 数组索引的类型:有符号/无符号整数先锋
- 使用链式#define来声明纯语言的整数索引是个好主意吗?
- 从整数索引的for循环枚举到range-for