/* Introduction
to program:
Program
- inssort.c.
Sorts
a user-inputed list using the insertion sort algorithm.
Francis
O'Donovan 29-12-97. */
/* Files to be #included. */
#include <stdio.h>
/* #definitions. */
#define LENGTH 10 /* Number of elements in list. */
/* Function: main() */
void main()
{
/* Variable definitions. */
int i, j, k;
/* Counters. */
int key;
/* key for Insertion sort algorithm. */
int A[ LENGTH]; /* List which user will fill
with values. */
/* Print introduction on screen. */
printf( "Program: inssort.c.\n\n" );
printf( "Sorts a user-inputed list using the insertion sort"
);
printf( " algorithm.\n\n" );
printf( "Francis O'Donovan 29-12-97.\n\n" );
/* Input list from user. */
printf( "Please type in the list of integers, pressing return
" );
printf( "after each element.\n\n" );
for ( i = 0; i < LENGTH; i++ )
{
printf( "Element %d: ", i+1 );
scanf( "%d", &A[i] );
}
/* Sort the list using the Insertion Sort algorithm. */
for ( j = 1; j < LENGTH; j++ ) /* Goes through list*/
{
key = A[j];
/* Set the new key to A[j]. */
k = j - 1;
/* Go through list from right. */
while ( ( k >= 0) && ( A[k] > key ) )
/* Do this until you reach the start of the list,
or you find the correct placement for key. */
{
A[k+1] = A[k];
/* Move kth element to (k+1)th position. */
k--;
}
A[k+1] = key;
/* Put key in (k+1) position. */
}
/* Print out list. */
for ( i = 0; i < LENGTH; i++)
{
printf( "%d ", A[i] );
}
}
© Francis O'Donovan
1999.