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

#include <stdio.h>

void bubble (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 */
    bubble (list, a);

    /* close file */
    fclose (infile);

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

    exit(1);

}

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

    int i, j, t;

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

