首页 > 解决方案 > 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 数字如何导致分段错误。有人可以帮我吗?

标签: c++

解决方案


推荐阅读