/*--------------------------------------------------------------------*/ /* sort5.c */ /* Author: Bob Dondero */ /* The standard qsort() function */ /*--------------------------------------------------------------------*/ #include #include #include enum {INITIAL_ARRAY_LENGTH = 2}; enum {ARRAY_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 iCount; int iLength; double dNumber; int i; /* Dynamically allocate an array. */ iLength = INITIAL_ARRAY_LENGTH; pdArray = (double*)calloc((size_t)iLength, sizeof(double)); assert(pdArray != NULL); /* Read the numbers into the array. */ iCount = 0; while (scanf("%lf", &dNumber) != EOF) { if (iCount == iLength) { iLength *= ARRAY_GROWTH_FACTOR; pdArray = (double*)realloc(pdArray, iLength * sizeof(double)); assert(pdArray != NULL); } pdArray[iCount] = dNumber; iCount++; } /* Sort the array. */ qsort(pdArray, (size_t)iCount, sizeof(double), compareDouble); /* Write the numbers from the array. */ for (i = 0; i < iCount; i++) printf("%g\n", pdArray[i]); /* Free the array. */ free(pdArray); return 0; }