C++ 在我的递归函数中堆栈溢出,是由于逻辑还是由于大数?

C++ 在我的递归函数中堆栈溢出,是由于逻辑还是由于大数?,c++,recursion,stack-overflow,C++,Recursion,Stack Overflow,当我在一个小数组上运行我的函数时,它工作得很好。然而,当我使用一个大数组时,我会不断得到堆栈溢出。 这是因为我的代码中的逻辑不正确吗?还是只是花了很长时间 void RecursiveSort(T data[], int first, B last) { // Sorts the array elements a[first] through a[last] recursively. // base case is if first and last are the same

当我在一个小数组上运行我的函数时,它工作得很好。然而,当我使用一个大数组时,我会不断得到堆栈溢出。 这是因为我的代码中的逻辑不正确吗?还是只是花了很长时间

void RecursiveSort(T data[], int first, B last)
{

    // Sorts the array elements a[first] through a[last] recursively.

    // base case is if first and last are the same, which means we 
    // have no subarrays left to do



    if (first < last)
    {
        int minIndex = first;
        // replace first index of array with smallest of values in  the array 

        for (int index = first+1; index < last; index++)
        {
            if (data[index] < data[minIndex])
                // swap values
                minIndex = index;
        }   


        int temp = data[first];
        data[first] = data[minIndex];
        data[minIndex] = temp;



        RecursiveSort(data, first + 1, last);

    }


}
void RecursiveSort(T data[],int first,B last)
{
//将数组元素从[first]到[last]递归排序。
//基本情况是,如果第一个和最后一个是相同的,这意味着我们
//没有子数组可以做
如果(第一次<最后一次)
{
int minIndex=第一;
//用数组中的最小值替换数组的第一个索引
for(int index=first+1;index
您看到的堆栈溢出错误仅仅是因为堆栈的大小有限。每次调用递归函数时,都会使用一定量的内存来存储一些值,例如要返回的地址、函数参数的值等。有关更多信息,请参阅

根据经验,如果您的递归深度超过1000级,您可能会遇到麻烦

好消息是,您的代码是一个示例,其中递归调用是函数中的最后一条语句。这些函数可以很容易地转换为循环:

for (first = 0; first < last; ++first) {
     ...
}
for(first=0;first

或者,如果您确实需要创建递归排序,请不要尝试实现选择排序,而是查看Or,两者都可以使用递归实现。

您的程序的堆栈内存有限。这个内存有多大可能取决于您的编译器或操作系统

对于递归函数的每次调用,该函数的所有参数都放在堆栈上。这意味着每个调用将占用另一个大小块(last-first)*sizeof(T)

使用大数组(last-first)会更大,但这也意味着递归函数将被调用更多次

总的来说,您需要大约(last-first)*(last-first)*sizeof(T)/2+(last-first)*2*sizeof(int)的堆栈大小。看看这个公式,你可以看到当数组的大小增加时,堆栈是如何陷入麻烦的。

是的, 我也同意您将拥有有限的堆栈内存,但是您可以通过如下所述放置交换标志来减少递归调用

void recursive_bubble_sort(int *array, int size)
{
   bool swap = false;   // to avoid recursion call when no swapping is required
   for(int i=0; i+1 < size; ++i)
   {
      if(array[i] < array[i+1])
      {
         int tmp = array[i];
         array[i] = array[i+1];
         array[i+1] = tmp;

         swap = true;
      }
   }

   if(swap)
      recursive_bubble_sort(array, size);
}
void recursive\u bubble\u排序(int*array,int size)
{
bool swap=false;//在不需要交换时避免递归调用
对于(int i=0;i+1

<>或实现递归排序或合并排序,以减少栈。

我不认为排序器从递归函数调用中受益。它不会复制每个调用的整个数组,每次只传递指针(因为我理解作者在这里使用的是常规C++数组,而不是STL容器,所以它是指针传递的).Whoops,是的,你是对的,数组是作为指针复制的,所以堆栈的总大小将是(最后一个-第一个)*(sizeof(void*)+2*sizeof(int))。。。加上一些内存量,用于返回地址和本地变量,如
minIndex
index
temp
,这些也应保存在堆栈框架中。我只想说它将使用O(N)的内存。是的,O(N)是堆栈使用的正确关系。在我的回答中,我错误地得到了O(N^2),因为我假设整个数组都放在堆栈上。