我正在實施標準的 MergeSort 演算法。我收到運行時錯誤“檢測到堆疊粉碎”。此類錯誤的根本原因是什么以及如何防止我的代碼出現此錯誤?我看到控制元件即將合并功能,但在某個地方它變得混亂了。
#include<iostream>
using namespace std;
//this particular function will merge 2 sorted array
void merge(int arr[], int res[], int low, int mid, int high) {
int i=low,j=mid 1,k=high;
while(i<=mid && j<=high) //make sure that i remains within the end if left subarray and j remains within the end of right subarray
{
if(arr[i]<=arr[j])
res[k ]=arr[i ];
else
res[k ]=arr[j ];
}
while(i<=mid) // In case there are some elements left in left subarray, just copy it into result
res[k ]=arr[i ];
while(j<=high) //// In case there are some elements left in right subarray, just copy it into result
res[k ]=arr[j ];
//copy the result into original array
for( i=low;i<=high;i )
arr[i]=res[i];
}
void mergeSort(int arr[], int res[], int low, int high) {
//Don't forget to put the base case in recursion
if(high == low)
return;
int mid = low (high-low)/2;
mergeSort(arr,res,low,mid);
mergeSort(arr,res,mid 1,high);
merge(arr,res,low,mid,high);
cout<<"end of recursion"<<endl;
}
int main() {
int arr[] = {8,4,3,12,25,6,13,10};
// initialise resultant array (temporary)
int res[]= {8,4,3,12,25,6,13,10};
for(int i=0 ;i<8 ; i )
cout<<arr[i]<<" ";
cout<<endl;
mergeSort(arr,res,0,7);
for(int i=0 ;i<8 ; i )
cout<<arr[i]<<" ";
cout<<endl;
}
uj5u.com熱心網友回復:
問題出在你的merge日常生活中。如果您查看lowandmid是 6 和high7 的情況,這將在遞回結束時發生,回圈
while (i <= mid)
res[k ] = arr[i ];
最終會k越界執行。我認為您的意思是k要被初始化,low因為它應該與i.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507841.html
上一篇:C 模板函式遞回
