Hi All,
I wrote a program to read a file then sort it using up and down heapsort.. Yet, it only shows me the result correctly if there are less than 8 values, i have been trying to debug and still can't find where is the logic error.. Would you tell me where's the logic error?
Thanks..
Code:
#include<stdio.h>
int array[300000],maxElm,i,j,k;
void pullValues() {
printf("\nSorted Array\n");
maxElm = j;
for(i = 1; i <= j; i++) {
printf("%d\n", array[i]);
}
}
void upSort(int *array,int i) {
int v = array[i];
while((i > 1) && (array[i/2] < v))
{
array[i] = array[i/2];
i = i / 2;
}
array[i] = v;
}
void downSort(int *array,int i,int maxElm) {
int v = array[i];
int j = i * 2;
while(j <= maxElm)
{
if((j < maxElm) && (array[j] < array[j+1])) {
j++;
}
if(array[j] < array[j/2]) {
break;
}
array[j/2] = array[j];
j = j * 2;
}
array[j/2] = v;
}
main() {
FILE *fp;
printf("\nPlease input the number of entries (k): ");
scanf("%d", &maxElm);
if((fp = fopen("test_dat.txt", "r")) == NULL) {
printf("Failed to open test_dat.txt\n");
return 0;
} else {
printf("Success to open test_dat.txt\n");
while(!feof(fp)) {
for(i = 1 ; i <= maxElm; i++) {
fscanf(fp, "%d", &array[i]);
upSort(array,i);
}
}
}
j=maxElm;
for(i = 1; i <= j; i++) {
int temp;
temp=array[1];
array[1]=array[maxElm];
array[maxElm]=temp;
maxElm--;
downSort(array,1,maxElm);
}
pullValues();
}