C ++代码可用于某些输入,但不适用于其他输入

时间:2019-10-12 02:39:31

标签: c++

我正在编写一个代码,该代码将对用户输入数组进行升序排序(使用quicksort),并使用递归函数查找数组中是否存在特定元素。我的quicksort函数可以工作,但是我在为递归搜索函数找到正确的答案时很挣扎。

这是我的主要

 #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数如何导致细分错误。有人可以帮我吗?

0 个答案:

没有答案