/*------------------------------------------------------------------*/ /* sort4.c (A Dynamically Expanding Array) */ /*------------------------------------------------------------------*/ #include #include #include #define INITIAL_LENGTH 2 /*------------------------------------------------------------------*/ void insertionSort(double *pdArray, int iNumberCount) /* Sort pdArray[0..iNumberCount-1] in ascending order. */ { int i1; int i2; double dTemp; for (i1 = 1; i1 < iNumberCount; i1++) for (i2 = i1; i2 > 0; i2--) if (pdArray[i2] < pdArray[i2-1]) { dTemp = pdArray[i2]; pdArray[i2] = pdArray[i2-1]; pdArray[i2-1] = dTemp; } } /*------------------------------------------------------------------*/ 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. */ insertionSort(pdArray, iNumberCount); /* Write the numbers from the array. */ for (i = 0; i < iNumberCount; i++) printf("%g\n", pdArray[i]); /* Free the array. */ free(pdArray); return 0; }