A SIMPLE EXCHANGE SORT ALGORITHM
The following steps define an algorithm for sorting an array,
1. Set i to 0 2. Set j to i + 1 3. If a[i] > a[j], exchange their values 4. Set j to j + 1. If j < n goto step 3 5. Set i to i + 1. If i < n - 1 goto step 2 6. a is now sorted in ascending order. Note: n is the number of elements in the array.
EXERCISE C18
Implement the above algorithm as a function in C, accepting the
array and its size, returning the sorted array in ascending order
so it can be printed out by the calling module. The array should
consist of ten elements.
#include <stdio.h> void sort( int [], int ); void sort( int a[], int elements ) { int i, j, temp; i = 0; while( i < (elements - 1) ) { j = i + 1; while( j < elements ) { if( a[i] > a[j] ) { temp = a[i]; a[i] = a[j]; a[j] = temp; } j++; } i++; } } main() { int numbers[] = { 10, 9, 8, 23, 19, 11, 2, 7, 1, 13, 12 }; int loop; printf("Before the sort the array was \n"); for( loop = 0; loop < 11; loop++ ) printf(" %d ", numbers[loop] ); sort( numbers, 11 ); printf("After the sort the array was \n"); for( loop = 0; loop < 11; loop++ ) printf(" %d ", numbers[loop] ); }