c++ - C++ 代码适用于某些输入,但不适用于其他输入
问题描述
我正在编写一个代码,它将按升序(使用快速排序)对用户输入数组进行排序,并使用递归函数来查找数组中的特定元素是否存在。我的快速排序功能有效,但我正在努力获得递归搜索功能的正确答案。
这是我的主要
#include <iostream>
#include <string>
using namespace std;
int recursivesearch(int arr[], int start, int end,int no);
int main () {
int no,size; // 'no' is what element to search, should be 1 in this case
cout << "Enter what to search" << endl; // element we need to search
cin >> no;
cout << endl;
cout << "Enter size of array" << endl; // array size im testing is 8
cin >> size;
int array[size];
for (int i=0;i<size;i++) {
cin >> array[i];
}
if (recursivesearch(array,0,size-1,no)==0) {
cout << "false" << " ";
}
else {
cout << "true" << " ";
}
cout << endl;
}
这是递归函数
int recursivesearch(int arr[], int start, int end, int number) {
int middle=0;
int element=number;
int length=(end-start)+1;
if (length%2!=0) { // defining the size depending on if its even or odd
middle=(start+end)/2;
}
else {
middle=(start+end)/2+1;
}
if (arr[middle]==element){ // base case, if we find it, return the index
return middle;
}
else if (length==1 && arr[middle]!=element) { // if we can't find it return 0
return 0;
}
else if (arr[middle]>element) {
recursivesearch(arr,start,middle-1,element); // if the middle index has value greater than element, call recursion for the left-hand side of the array from the middle point
}
else if (arr[middle]<element) { // if the middle index has value less than element, call recursion for the RHS from the middle point
recursivesearch(arr,middle+1,end,element);
}
}
我只测试数字“1”是否在数组中,因为这是我指定要做的。这仅适用于特定情况。如果我写 [-5 1 3 4 5 100 2014 7777] 它可以工作(显示为真)。但是如果我写 [-5 0 1 3 4 5 100 2014 7777] 我会遇到分段错误。我不明白更改 1 数字如何导致分段错误。有人可以帮我吗?
解决方案
推荐阅读
- rest - HTTP 和 REST:状态代码与请求相关还是与资源相关?
- javascript - “发布”和“获取”问题,我无法在我的餐桌上添加或删除员工
- c# - 将 .proto 文件从 nugetpackage 导入另一个 proto 文件
- logging - 无法使用 Filebeat 在 Grok 中解析没有 IP 地址的 haproxy 日志
- arrays - 在 Google 表格中删除逗号后的空格
- java - Java - 获取本月的第一个星期四
- javascript - json从mySql数据库到对象数组的转换
- python - 为什么 BeautifulSoup 不抓取整个网页并获取它?
- c# - 通过项目互操作在 MPP 中的多个过滤条件
- linux - 在 linux 中的 mailx 命令的邮件中将 .txt 文件的内容添加到邮件正文中