我正在尝试编写一个带有指针的合并排序程序,它几乎可以正常工作,但问题是在输出中有一些“0”而不是排序数组的一些数字。
为了测试代码,您必须编写一个 txt 文件prova.txt
,其中包含数组,行数为一个。例如:
prova.txt:
4
7
2
9
1
45
87
运行代码时,我期望输出
0: 1
1: 2
2: 4
3: 7
4: 9
5: 45
6: 87
但我明白了
0: 1
1: 0
2: 0
3: 0
4: 0
5: 0
6: 2
此外,你有什么建议可以给我改进我的代码吗?
#include <stdio.h>
int *merge(int left[], int right[], int n){
int *ordinato, i=0, j=0;
ordinato = malloc(sizeof(int)*n);
while(i+j < n){
if(left[i] < right[j]){
*(ordinato+i+j) = left[i];
i++;
}else{
*(ordinato+i+j) = right[j];
j++;
}
}
return ordinato;
}
int *mergeSort(int *daOrd, int n){
int k = 0, *left, *right, *ordinato;
ordinato = malloc(sizeof(int)*n);
left = malloc(sizeof(int)*(n/2));
right = malloc(sizeof(int)*(n-(n/2)));
if (n<2){
ordinato = daOrd;
}else{
for(k=0; k<n/2; k++)
*(left + k) = *(daOrd + k);
for(k=n/2; k<n; k++)
*(right + k -(n/2)) = *(daOrd + k);
left = mergeSort(left, n/2);
right = mergeSort(right, n-(n/2));
ordinato = merge(left, right, n);
}
return ordinato;
}
main(){
FILE *input;
input = fopen("prova.txt", "r");
if(!input) printf("Errore");
int tot = 100000;//is the maximum n
int *array;
array = malloc(sizeof(int)*tot);
int indice = 0;
while(fscanf(input,"%d", (array + indice)) != EOF) indice++;
int *ord = mergeSort(array, indice);
int k;
for(k=0; k<indice; k++) printf("%d: %d \n",k, *(ord+k));
getch();
fclose(input);
}