/*------------------------------------------------------------------*/ /* sort5.c (The Standard qsort Function) */ /*------------------------------------------------------------------*/ #include #include #include #define INITIAL_LENGTH 2 /*------------------------------------------------------------------*/ int compareDouble(const void *pvItem1, const void *pvItem2) /* Return -1, 0, or 1 depending upon whether *pvItem1 is less than, equal to, or greater than *pvItem2, respectively. */ { double *pdItem1 = (double*)pvItem1; double *pdItem2 = (double*)pvItem2; 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(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, iNumberCount, sizeof(double), 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; }