// ----- Example: Selection Sort ----- // // This program reads in an array of doubles up to MAX_LENGTH elements // long and sorts its entries. The elements in the array are then printed // in sorted order. // ----------------------------------------------- #include using namespace std; const int MAX_LENGTH = 1000; void select_sort( double[] , int ); void swap ( double& , double& ); int indexOfLeast( double[] , int ); int main() { double a[MAX_LENGTH]; // Get input. int i, n; cout << "\n Enter the number of elements to be sorted: "; cin >> n; cout << "\n Enter the elements one by one (no commas): \n\n"; for (i = 0; i < n; ++i) { cout << "enter a[" << i << "]: "; cin >> a[i]; } select_sort( a, n ); // Sort it. cout << " \n The sorted array is: \n\n"; // Print output. i=0; while ( i < n ) { cout << a[i] << " "; ++i; } cout << "\n\n"; return 0; } void select_sort( double a[], int length ) { int i, i_min; // Recursively swap the first element for ( i = 0; i < length-1; ++i ) // of the unsorted part of a[] with a { // least element of the unsorted part. i_min = i + indexOfLeast( a+i, length -i ); if (i_min > i) swap ( a[i], a[i_min] ); } } void swap ( double& a, double& b) { double t = a; a = b; b = t; } int indexOfLeast( double a[], int length ) { int i, answer = 0; double leastElement = a[0]; // The least element examined so far. for (i = 1; i < length; i++ ) if ( a[i] < leastElement ) { leastElement = a[i]; answer = i; } return answer; }