/* 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 #define INBUF_SZ 1024 /* bubble_sort - * sorts, in place, N floating point numbers in the array pointed to by e. */ void bubble_sort(float *e, int N) { int i, j, swapped; float tmp; for (i=N-1,swapped=1; i>=0 && swapped; i--) for (j=0,swapped=0; j < i; j++) { if (e[j+1] < e[j]) { tmp = e[j+1]; e[j+1] = e[j]; e[j] = tmp; swapped=1;} } } int main(int argc, char *argv[]) { FILE *fh; int i, N_entries; 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 the number of entries in the file */ for (i = 0; fgets(inbuf, INBUF_SZ, fh); i++); N_entries = i; /* allocate enought 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]); fclose(fh); /* sort them */ bubble_sort(entries, N_entries); /* display the result */ for (i=0; i