C++ examples for Data Structure:Sort
Selection sort with pass-by-reference.
#include <iostream> #include <iomanip> using namespace std; void selectionSort( int * const, const int ); // prototype void swap( int * const, int * const ); // prototype int main() /* w ww . j a v a 2 s .c o m*/ { const int arraySize = 10; int a[ arraySize ] = { 12, 6, 4, 18, 10, 12, 89, 68, 45, 37 }; for ( int i = 0; i < arraySize; ++i ) cout << setw( 4 ) << a[ i ]; selectionSort( a, arraySize ); // sort the array for ( int j = 0; j < arraySize; ++j ) cout << setw( 4 ) << a[ j ]; cout << endl; } void selectionSort( int * const array, const int size ) { int smallest; // index of smallest element // loop over size - 1 elements for ( int i = 0; i < size - 1; ++i ) { smallest = i; // first index of remaining array // loop to find index of smallest element for ( int index = i + 1; index < size; ++index ) if ( array[ index ] < array[ smallest ] ) smallest = index; swap( &array[ i ], &array[ smallest ] ); } } void swap( int * const element1Ptr, int * const element2Ptr ) { int hold = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = hold; }