/* File: bubble4.c Bubblesort This one uses lots of functions and reads input from a file. */ #include #include #define A_SIZE 100 void swap(int *ptr1, int *ptr2) ; void PrintArray(int A[], int size) ; void BubbleSort(int A[], int size) ; int ReadArray(int A[], char fname[], int max_size) ; int main() { int A[A_SIZE], n ; n = ReadArray(A, "data25.txt", A_SIZE) ; if ( n > 0 ) { printf("Read in %d numbers into array A[].\n", n) ; } else { printf("No numbers read into array A[]. Missing file??\n") ; return 0 ; } printf("Before sorting: ") ; PrintArray(A, n) ; BubbleSort(A, n) ; printf("After sorting: ") ; PrintArray(A, n) ; return 0 ; } void BubbleSort(int A[], int size) { int i, j ; for (i = 0 ; i < size - 1 ; i++) { for (j = 0 ; j < size - i - 1 ; j++) { if (A[j] > A[j+1]) { swap(&A[j], &A[j+1]) ; } } } } void PrintArray (int A[], int size) { int i ; for ( i = 0 ; i < size ; i++ ) { printf("%2d ", A[i]) ; } printf("\n") ; } void swap(int *ptr1, int *ptr2) { int temp ; temp = *ptr1 ; *ptr1 = *ptr2 ; *ptr2 = temp ; } /* ReadArray Opens the file specified by fname and reads integers into array A[], but not more than max_size items. Return value: positive number = # of integers read 0 = empty file negative number = error encountered */ int ReadArray(int A[], char *fname, int max_size) { FILE *iFile ; int i, r, input ; // open fname for reading iFile = fopen(fname, "r") ; // open successful? if (iFile == NULL) { return -1 ; } i = 0 ; while(1) { r = fscanf(iFile, "%d", &input) ; // end-of-file or not a number? if (r <= 0) { break ; } // store new number A[i] = input ; i++ ; // reached end of file? if (i == max_size) { // fprintf(stderr, "Array limit reached.\n") ; break ; } // This shouldn't ever happen! if (i > max_size) { fprintf(stderr, "Somehow, i > max_size!\n") ; abort() ; } } fclose(iFile) ; return i ; }