我正在嘗試合并兩個排序的子陣列。我花了數小時的挫敗感來消除vs 代碼中的分段錯誤,但沒有成功。
- 我正在使用一個臨時陣列來存盤新排序的陣列。
- 同時比較兩個子陣列的元素,并增加arr[index]較小的子陣列的索引。
- 復制遍歷索引尚未到達末尾的子陣列的剩余元素。
#include<iostream>
#include<math.h>
using namespace std;
void merge(int start1,int end1,int start2,int end2,int arr[],int temp_arr[]){
int i = start1;
int j = start2;
while (i <= end1 && j <= end2)
{
if(arr[i] < arr[j]){
//using start1 as index on purpose
temp_arr[start1 ] = arr[i];
i ;
}else{
temp_arr[start1 ] = arr[j];
j ;
}
}
//if first array elements are left
while(i <= end1 ){
temp_arr[start1 ] = arr[i];
}
//if second array elements are left
while(j <= end2){
temp_arr[start1 ] = arr[j];
}
}
int main(){
int arr[] = {5,6,7,1,2,3};
int n = sizeof(arr)/sizeof(int);
int temp[n];//temporary array
int a;
//to find where the next sorted subarray begins
for(int i = 0;i <n-1;i ){
if(arr[i] > arr[i 1]){
a= i;
break;
}
}
merge(0,a,a 1,n-1,arr,temp);
for(int i = 0;i < n;i ){
cout << temp[i] << " ";
}
}
uj5u.com熱心網友回復:
這是一個無限回圈:
while(i <= end1 ){
temp_arr[start1 ] = arr[i];
}
這個也是。
while(j <= end2){
temp_arr[start1 ] = arr[j];
}
在這兩種情況下,因為無論是i,j,end1,也end2曾經在這些回圈發生變化,start1將不斷增加的方式越過陣列邊界,就使分配每一次迭代中引入更多不確定的行為。
這可能不是你唯一的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409057.html
標籤:
