With arrays, we can sort a list of integers entered by the
user. This program uses an algorithm
called "Selection Sort" to put the numbers in increasing order.
The Program
/****************************************
** File: sort.c
** Author: Richard Chang
** Date Written: ?
** Modified by: Sue Bogar
** Modification date: 2/25/98
** Section: 101
** SSN: 123-45-6789
** EMail: bogar@cs.umbc.edu
** Sort a list of numbers using an array
** and selection sort.
*****************************************/
#include
/* sentinel input value */
#define SENTINEL -1
/* max number of values to be sorted */
#define MAX 100
/* function prototypes */
int ReadArray (int a[], int maxSize) ;
void SelectionSort (int a[], int size) ;
int FindSmallest (int a[], int start, int stop) ;
int main ( )
{
int a[MAX], items, i ;
printf("Enter items, one per line.\n") ;
printf("End with sentinel: %d\n", SENTINEL) ;
items = ReadArray(a, MAX) ;
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]) ;
}
}
return 0;
}
/*********************************************
** Function: SelectionSort
** Input: an array of ints to be sorted
** the size of the array
** Output: the array is sorted "in place"
** there is no return value
** Description:
** Selection sort finds the smallest value
** in the unsorted portion of the array and
** moves it into the current position. The
** values "swap" positions.
**********************************************/
void SelectionSort(int a[], int size)
{
int unsorted, smallestIndex, temp ;
for (unsorted = 0; unsorted < size;
unsorted++)
{
smallestIndex =
FindSmallest(a, unsorted, size);
/* swap values */
temp = a[smallestIndex] ;
a[smallestIndex] = a[unsorted] ;
a[unsorted] = temp ;
}
}
/*********************************************
** Function: FindSmallest
** Input: an array of ints to search
** the 'start'ing and 'stop'ping indices in
** the array between which to search for
** the smallest
** Output: returns the smallest value
** between a[start] and a[stop - 1]
**********************************************/
int FindSmallest(int a[], int start, int stop)
{
int smallestValue, smallestIndex, i ;
smallestIndex = start ;
smallestValue = a[start] ;
for (i = start+1 ; i < stop ; i++)
{
if (a[i] < smallestValue)
{
smallestIndex = i ;
smallestValue = a[i] ;
}
}
return (smallestIndex) ;
}
/*********************************************
** Function: ReadArray
** Input: an array of ints in which to store values
** the size of the array
** Output: values are stored the array
** returns the number of elements stored in
** the array or returns -1 if too many
** values are read
**********************************************/
int ReadArray(int a[], int maxSize)
{
int i, value ;
i = 0 ;
/* The priming read */
scanf ("%d", &value);
while (value != SENTINEL)
{
if (i == maxSize)
{
return(-1) ;
}
a[i] = value ;
i++ ;
scanf ("%d", &value);
}
return (i) ;
}