已解决!!!归并排序出错,求帮看,不胜感激
已解决:
for ( i = 0; i <=k ; i++)
a[first+i] = b[i];
应该改为
for ( i = 0; i <k ; i++)
a[first+i] = b[i];
因为最后又++了一次k值变为数列长度
可能与k值有关,更改k之后,不再出现前面那几个 -842150451 了,但是更改之后程序明显是不对的。
运行时提示:stack around variable“Arr” was corrupted
错误结果如下:
//归并排序
#include<iostream>
using namespace std;
//将两个已排数列a[first~mid]和a[mid+1~last]合并为b[]
void mergeArr(int a[],int first,int mid, int last, int b[])
{
int i = first;
int m = mid;
int j = mid + 1;
int n = last;
int k = 0;
while (i <=m && j <= n)
{
if (a[i] < a[j])
b[k++] = a[i++];
else
b[k++] = a[j++];
}
while (i <= m)
b[k++] = a[i++];
while (j <= n)
b[k++] = a[j++];
for ( i = 0; i <=k ; i++)
a[first+i] = b[i];
}
//递归
void mergeSort(int a[], int first, int last, int b[])
{
if (first < last)
{
int mid = (first + last)/2;
mergeSort(a, first, mid, b); //左排序
mergeSort(a, mid + 1, last, b); //右排序
mergeArr(a, first, mid, last, b); //合并
}
}
bool MergeSort(int a[], int size)
{
int *p = new int[size];
if (p == NULL)
return false;
mergeSort(a, 0, size - 1, p);
delete[] p;
return true;
}
void main()
{
int Arr[12] = { 10, 98, 3, 48, 5, 59, 1, 101, 25, 34, 54, 565 };
MergeSort(Arr, 12);
for (int i = 0; i < 12;i++)
cout << Arr[i]<<" ";
cout << endl;
}