/* File: sort.c Sort a list of numbers. */ #include #include "genlib.h" #include "simpio.h" #define SENTINEL -1 #define MAX_ITEMS 100 int ReadArray(int A[], int max_size) ; void SelectionSort(int A[], int size) ; int FindSmallest(int A[], int start, int stop) ; main() { int A[MAX_ITEMS], items, i ; printf("Enter items, one per line.\n") ; printf("End with sentinel: %d\n", SENTINEL) ; items = ReadArray(A, MAX_ITEMS) ; if (items == -1) { printf("Too many items!!!\n") ; } else { SelectionSort(A, items) ; printf("\nSorted list:\n") ; for(i = 0 ; i < items ; i++) { printf("A[%d] = %d\n", i, A[i]) ; } } } /* Use Selection Sort to sort the array */ void SelectionSort(int A[], int size) { int unsorted, smallest_index, temp ; for(unsorted=0; unsorted < size-1; unsorted++){ smallest_index = FindSmallest(A,unsorted,size-1); /* swap values */ temp = A[smallest_index] ; A[smallest_index] = A[unsorted] ; A[unsorted] = temp ; } } /* Find smallest value in array A from start to stop. */ int FindSmallest(int A[], int start, int stop) { int smallest_value, smallest_index, i ; smallest_index = start ; smallest_value = A[start] ; for (i = start+1 ; i <= stop ; i++){ if (A[i] < smallest_value) { smallest_index = i ; smallest_value = A[i] ; } } return(smallest_index) ; } /* Read integers into array. Make sure that array size is not exceeded. If so, return -1, otherwise return # of items. */ int ReadArray(int A[], int max_size) { int i, value ; i = 0 ; while (TRUE) { value = GetInteger() ; if (value == SENTINEL) break ; if (i == max_size) return(-1) ; A[i] = value ; i++ ; } return(i) ; }