/*------------------------------------------------------------------*/ /* sort6.c (The Standard qsort Function, Casting of Function */ /* Pointers) */ /*------------------------------------------------------------------*/ #include #include #include #define INITIAL_LENGTH 2 /*------------------------------------------------------------------*/ static int compareDouble(double *pdItem1, double *pdItem2) /* Return -1, 0, or 1 depending upon whether *pdItem1 is less than, equal to, or greater than *pdItem2, respectively. */ { if (*pdItem1 < *pdItem2) return -1; if (*pdItem1 > *pdItem2) return 1; return 0; } /*------------------------------------------------------------------*/ int main(int argc, char *argv[]) /* Read numbers from stdin, and write them in ascending order to stdout. */ { double *pdArray; int iNumberCount; int iLength; double dNumber; int i; /* Dynamically allocate an array. */ iLength = INITIAL_LENGTH; pdArray = (double*)calloc((size_t)iLength, sizeof(double)); assert(pdArray != NULL); /* Read the numbers into the array. */ iNumberCount = 0; while (scanf("%lf", &dNumber) != EOF) { if (iNumberCount == iLength) { iLength *= 2; pdArray = (double*)realloc(pdArray, iLength * sizeof(double)); assert(pdArray != NULL); } pdArray[iNumberCount] = dNumber; iNumberCount++; } /* Sort the array. */ qsort(pdArray, (size_t)iNumberCount, sizeof(double), (int(*)(const void*, const void*))compareDouble); /* Write the numbers from the array. */ for (i = 0; i < iNumberCount; i++) printf("%g\n", pdArray[i]); /* Free the array. */ free(pdArray); return 0; }