c - Why my 'mergesort' fails at large # of numbers?
问题描述
I have a code of mergesort, it works well with N=68,000 or less, but when the # of numbers increase to 70,000, there's error that some of the elements are not sorted. My friend guess it's because I used too many malloc, but I don't know why.
keytype is just an "unsigned long" type defined by myself. A is a pre-set array by keytype* A = (keytype *)malloc(N * sizeof(keytype)); and filled by random numbers.
typedef unsigned long keytype;
keytype *new_part(int start, int end, keytype* A) {
int N = end - start + 1;
keytype* cc = (keytype *)malloc(N * sizeof(keytype));
for (int i = 0; i < N; i++) {
cc[i] = A[start + i];
}
return cc;
}
void mySort(int N, keytype* A){
if (N == 1) return;
int mid = N / 2;
keytype* first = new_part(0, mid - 1, A);
keytype* second = new_part(mid, N - 1, A);
mySort(mid, first);
mySort(N - mid, second);
int a = 0, b = 0;
for (int i = 0; i < N; i++) {
if (a >= mid) {
A[i] = second[b];
b++;
continue;
}
if (b >= N - mid) {
A[i] = first[a];
a++;
continue;
}
if (first[a]>second[b]) {
A[i] = second[b];
b++;
continue;
}
if (first[a] < second[b]) {
A[i] = first[a];
a++;
continue;
}
}
free(first);
free(second);
}
解决方案
推荐阅读
- docker - Docker 解决方案,用于在多个容器之间分发文件内容并将输出合并到一个文件中
- azure-sql-database - Azure SQL 数据库的 SSMS 索引提示
- r - 绘制一段时间内的数据趋势
- react-native - 无法在 React Native Share 中分享产品图片
- r - bigrquery - 错误:没有匹配的运算符签名 - 对于参数类型:DATE、FLOAT64
- c - free() 调用中的 _snwprintf_s 堆损坏错误
- mysql - 比较两个表后如何输出匹配?
- python - 如何将外部对象附加到系列索引
- reactjs - 如何在反应js中调用从一个组件到另一个组件的方法(在新选项卡中)
- android - 响应 Delphi 中的媒体按钮