当我尝试 运行 时,此代码输出是 "merge.exe has stopped working"?
When i try to run this code output is "merge.exe has stopped working"?
#include<iostream>
#define INF 10000
using namespace std;
void mergeSort(int *x,int y,int z);
void merge(int *a,int p,int q,int r);
void main()
{
int i,size;
cin>>size;
int arr[size];
for(i=0;i<size;i++)
{
cin>>arr[i];
}
mergeSort(arr,0,size-1);
for(i=0;i<size;i++)
{
cout<<arr[i]<<endl;
}
}
This function takes in the array to be sorted and the values of starting and ending index i.e, y,z.
void mergeSort(int *x,int y,int z)
{
int q;
if(y<z)
{
q=(y+z)/2;
mergeSort(x,y,q);
mergeSort(x,q+1,z);
merge(x,y,q,z);
}
}
this function merges two sorted sections of the array and p,r are starting and ending index while q is the index which divides the array into two sorted parts
void merge(int *a,int p,int q,int r)
{
int l1,l2,i,j;
l1=q-p+1;
l2=r-q;
int left[l1+1],right[l2+1];
for(int i=0;i<l1;i++)
{
left[i]=a[p+i];
}
for(int j=0;j<l2;j++)
{
right[i]=a[q+j];
}
left[l1+1]=INF;
right[l2+1]=INF;
i=0;
j=0;
for(int k=0;k<=r-p;k++)
{
if(left[i]<right[j])
{
a[k]=left[i++];
}
else
{
a[k]=right[j++];
}
}
}
您已尝试在以下行中(在 merge()
子例程中)访问 越界索引 :
left[l1 + 1] = INF;
right[l2 + 1] = INF;
大小分别为l1+1
和l2+1
。因此,有效索引的范围将是 [0, l1]
和 [0, l2]
。因此,这些行应该是:
left[l1] = INF;
right[l2] = INF;
最后的问题在行中:
for(int k = 0; k <= r-p; k++)
应该是
for(int k = p; k <= r; k++)
否则,您只会覆盖其他值。您必须将合并的部分插入到正确的位置。
#include<iostream>
#define INF 10000
using namespace std;
void mergeSort(int *x,int y,int z);
void merge(int *a,int p,int q,int r);
void main()
{
int i,size;
cin>>size;
int arr[size];
for(i=0;i<size;i++)
{
cin>>arr[i];
}
mergeSort(arr,0,size-1);
for(i=0;i<size;i++)
{
cout<<arr[i]<<endl;
}
}
This function takes in the array to be sorted and the values of starting and ending index i.e, y,z.
void mergeSort(int *x,int y,int z)
{
int q;
if(y<z)
{
q=(y+z)/2;
mergeSort(x,y,q);
mergeSort(x,q+1,z);
merge(x,y,q,z);
}
}
this function merges two sorted sections of the array and p,r are starting and ending index while q is the index which divides the array into two sorted parts
void merge(int *a,int p,int q,int r)
{
int l1,l2,i,j;
l1=q-p+1;
l2=r-q;
int left[l1+1],right[l2+1];
for(int i=0;i<l1;i++)
{
left[i]=a[p+i];
}
for(int j=0;j<l2;j++)
{
right[i]=a[q+j];
}
left[l1+1]=INF;
right[l2+1]=INF;
i=0;
j=0;
for(int k=0;k<=r-p;k++)
{
if(left[i]<right[j])
{
a[k]=left[i++];
}
else
{
a[k]=right[j++];
}
}
}
您已尝试在以下行中(在 merge()
子例程中)访问 越界索引 :
left[l1 + 1] = INF;
right[l2 + 1] = INF;
大小分别为l1+1
和l2+1
。因此,有效索引的范围将是 [0, l1]
和 [0, l2]
。因此,这些行应该是:
left[l1] = INF;
right[l2] = INF;
最后的问题在行中:
for(int k = 0; k <= r-p; k++)
应该是
for(int k = p; k <= r; k++)
否则,您只会覆盖其他值。您必须将合并的部分插入到正确的位置。