/* Author: Ben Miller
*  This is a copy of Sedgewick's selectionsort out of his book Algorithms
*  in C.  The program sorts a list up to a million in length.
*/

#include <stdio.h>

void selection (int list[], int N);

int main (int argc, char *argv[]) {

    FILE *infile;
    char unsorted_file[25];
    int list[1000000];
    int number, a;

    /* check command line */
    if (argc != 2) {
	printf ("Error entering correct number of arguements.\n");
	printf ("Enter the name of the unsorted file. ");
	scanf ("%s", unsorted_file);
    } else
	strcpy (unsorted_file, argv[1]);

    /* check if file is equal to null */
    if ((infile = fopen(unsorted_file, "r")) == NULL) {
	printf ("Error opening file: %s.\n", unsorted_file);
	exit (1);
    }

    /* read the file into an array */
    while (fscanf(infile, "%d", &number) != EOF) {
	list[a] = number;
	a++;
    }

    /* sort the array */
    selection (list, a);

    /* close file */
    fclose (infile);

    /* print completed */
    printf ("Completed!! The list has been sorted.\n");

    exit(1);

}

void selection (int a[], int N) {

    int i, j, min, t;

    for (i = 0; i < N; i++) {
	min = i;
	for (j = i+1; j <= N; j++)
	    if (a[j] < a[min])
		min = j;
	    t = a[min];
	    a[min] = a[i];
	    a[i] = t;
    }
    return;
}

