/* 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 SZ_INBUF 1024 void selection_sort(float *entries, int N_entries) { int i, j, min_idx; for (i = 0; i < N_entries; i++) { float swap_tmp; /* find minimum value in the range i..(N_entries-1) */ for (j = i+1, min_idx = i; j < N_entries; j++) if (entries[j] < entries[min_idx]) min_idx = j; /* if needed, swap i-th entry with min_idx entry */ if (i == min_idx) continue; swap_tmp = entries[i]; entries[i] = entries[min_idx]; entries[min_idx] = swap_tmp; } } int main(int argc, char *argv[]) { FILE *fh; int i, N_entries; float *entries; char *file_name, inbuf[SZ_INBUF]; 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; } /* count entries to sort */ for (i = 0; fgets(inbuf, SZ_INBUF, fh); i++); N_entries = i; /* allocate space to store them */ if (!(entries = malloc(sizeof(float)*N_entries))) { fprintf(stderr, "Out of memory!\n"); return -1; } fseek(fh, 0, SEEK_SET); /* read them in */ for (i=0; fgets(inbuf, SZ_INBUF, fh); i++) sscanf(inbuf,"%f\n",&entries[i]); fclose(fh); /* sort them */ selection_sort(entries, N_entries); /* display the results */ for (i = 0; i < N_entries; i++) printf("%f\n", entries[i]); free(entries); return 0; }