C/Qsort function
Expert: Narendra - 9/24/2005
QuestionHello,
I was doing some search online and I found this link and decided it try it out. Here is the problem I am having. I want to sort a multdimensional data according to the first column. First I tried to sort an array which contains doubles in th efollowing code by using the built in function qsort. But after run I just don't get the sorted array and I am wondering what it is happening. Input file will be assumed comma separated txt file.
note:I have only a week of experience with C and if it is a common question you don't even have to consider it. The compiler I ma using is lcc.
here is the code:
#include <stdlib.h>
#include <stdio.h>
//sort an array containing doubles:initial try!
int compare_doubles (const double * x,const double * y)
{
if (*x > *y)
return 1;
else if (*x < *y)
return -1;
else
return 0;
}
int main (){
int i=0,nROW,nCOL;
printf("Enter #ROWs: ");
scanf("%d",&nROW);
FILE *iPtr=fopen("in.txt","r");
float *a;
a= malloc(sizeof(double *)*nROW);
while (!feof(iPtr))
{
fscanf(iPtr,"%f,",&a[i]);
printf("%f\n",a[i]);
i++;
}
qsort(a, nROW, sizeof(double),compare_doubles);
printf("after sorting:\n");
for(i=0;i<nROW;i++)
{
printf("%f\n",a[i]);
}
return 0;
}
AnswerHere is your corrected code.
Compare it with your previous code and you will find the difference.
I have one suggestion for you. Whenever you program, follow a uniform indentation. It will help you and others in debugging the program. It will improve readability.
#include <stdlib.h>
#include <stdio.h>
//sort an array containing doubles:initial try!
int compare_doubles (const void *X, const void *Y)
{
double x = *((double *)X);
double y = *((double *)Y);
if (x > y)
{
return 1;
}
else
{
if (x < y)
{
return -1;
}
else
{
return 0;
}
}
}
int main ()
{
int i = 0, nROW;
printf("Enter #ROWs: ");
scanf("%d", &nROW);
FILE *iPtr = fopen("in.txt", "r");
double *a;
a = malloc(sizeof(double) * nROW);
while (!feof(iPtr))
{
fscanf(iPtr, "%lf,", &a[i]);
printf("%lf\n", a[i]);
i++;
}
qsort((void *)a, nROW, sizeof(double), compare_doubles);
printf("after sorting:\n");
for(i = 0; i < nROW; i++)
{
printf("%f\n", a[i]);
}
return 0;
}