/*------------------------------------------------------------------*/ /* sort5.c */ /* Author: Bob Dondero */ /* The standard qsort() function */ /*------------------------------------------------------------------*/ #include #include #include enum {INITIAL_LENGTH = 2}; enum {GROWTH_FACTOR = 2}; /*------------------------------------------------------------------*/ static 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. Return 0. */ { 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 *= GROWTH_FACTOR; pdArray = (double*)realloc(pdArray, iLength * sizeof(double)); assert(pdArray != NULL); } pdArray[iNumberCount] = dNumber; iNumberCount++; } /* Sort the array. */ qsort(pdArray, (size_t)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; }