数据结构与算法-归并排序
报错
1、栈溢出
//递归结束判断
if(size==1)
return ;
2、动态数组
int* temp = (int*)malloc((n1+n2) * sizeof(int));
...
free(temp);
防止栈溢出(递归太深)
3、无法解决的外部符号
在网上查了半天发现是函数名写错了,太不认真了!!!
代码
用递归实现(一定要有结束条件)
void merging(int* a, int n1, int* b, int n2)
{
//temp是临时数组
int* temp = (int*)malloc((n1+n2) * sizeof(int));
int i, j, k, m; m = i = j = k = 0;
while (i < n1 && j < n2)
{
if (a[i] < b[j])
{
temp[k++] = a[i++];
}
else
{
temp[k++] = b[j++];
}
}
while (i < n1)
{
temp[k++] = a[i++];
}
while (j < n2)
{
temp[k++] = b[j++];
}
for (m = 0; m < n1 + n2; m++)
{
a[m] = temp[m];
}
free(temp);
}
void Myqsort(int* array, int size)
{
if (size == 1) {
return;
}
int* a, * b;
//左半部分
int n1 = size / 2;
//右半部分
int n2 = size - n1;
a = array;
b = array + size / 2;
Myqsort(a, n1);
Myqsort(b, n2);
merging(a, n1, b, n2);
}