/* Copyright 2005 Daniel Cer (daniel.cer@cs.colorado.edu) This work is licensed under the Creative Commons Attribution-NonCommercial- ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. */ #include #include #include #define INBUF_SZ 1024 void insertion_sort(float *entries, int N_entries) { int i, j; float val; for (i = 1; i < N_entries; i++) { val = entries[i]; for (j = i-1; j > -1; j--) { if (entries[j] <= val) break; entries[j+1] = entries[j]; } entries[j+1] = val; } } int main(int argc, char *argv[]) { FILE *fh; int N_entries, i; float *entries; char *file_name, inbuf[INBUF_SZ]; if (argc != 2) { fprintf(stderr, "Usage:\n\t%s (file with numbers to sort)\n", argv[0]); return -1; } file_name = argv[1]; if (!(fh = fopen(file_name, "r"))) { fprintf(stderr, "Error opening \"%s\": %s\n", file_name, strerror(errno)); return -1; } /* determine number of entries in the file */ for (i = 0; fgets(inbuf, INBUF_SZ, fh); i++); N_entries = i; /* allocate enough memory to store them */ if (!(entries = malloc(sizeof(float)*N_entries))) { fprintf(stderr, "Out of memory!\n"); return -1; } /* read in the entries */ fseek(fh, 0, SEEK_SET); for(i=0; fgets(inbuf, INBUF_SZ, fh); i++) sscanf(inbuf, "%f\n", &entries[i]); /* sort them */ insertion_sort(entries, N_entries); /* display them */ for (i=0; i