#include #include #include const int True = 1; const int False = 0; void sel_sort( int [ ], int ); void swap( int*, int* ); int sorted( const int [ ], int, int ); main() { int a[ ] = { 5, 4, 3, 2, 1 }; int i; int n = 5; sel_sort( a, n ); for ( i = 0; i < n; i++ ) printf( "%d\n", a[ i ] ); return EXIT_SUCCESS; } void sel_sort( int a[ ], int n ) { int min_ind, i, j; for ( i = 0; i < n - 1; i++ ) { assert( i >= 0 ); assert( i < n ); min_ind = i; j = i + 1; /* find next smallest */ do { assert( j >= 0 ); assert( j < n ); assert( min_ind >= 0 ); assert( min_ind < n ); if ( a[ j ] < a[ min_ind ] ) min_ind = j; } while ( ++j < n ); assert( min_ind >= 0 ); assert( min_ind < n ); /* place next smallest at correct slot */ swap( &a[ i ], &a[ min_ind ] ); assert( sorted( a, i, n ) ); } } void swap( int *cell1, int *cell2 ) { int temp; temp = *cell1; *cell1 = *cell2; *cell2 = temp; } /* Returns True if a[ 0 ],a[ 1 ],...,a[ i ] are sorted and a[ j ] >= a[ i ] for all j, i < j < n. Returns False otherwise. */ int sorted( const int a[ ], int i, int n ) { int j; for ( j = 0; j <= i; j++ ) if ( a[ j ] > a[ j + 1 ] ) return False; for ( j = i + 1; j < n; j++ ) if ( a[ j ] < a[ i ] ) return False; return True; }