1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
// return the position of the smallest item at or after start_pos
int pos_smallest_item( const int array[], int size, int start_pos )
{
int pos_smallest = start_pos ;
for( int i = start_pos+1 ; i < size ; ++i )
if( array[i] < array[pos_smallest] ) pos_smallest = i ;
return pos_smallest ;
}
void swap( int array[], int i, int j ) // swap array[i] and array[j]
{
const int temp = array[i] ;
array[i] = array[j] ;
array[j] = temp ;
}
int selection_sort( int array[], int size ) // return number of swaps
{
int num_swaps = 0 ;
for( int i = 0 ; i < size-1 ; ++i )
{
const int pos_smallest = pos_smallest_item( array, size, i ) ;
if( array[pos_smallest] != array[i] ) // swap only if required
{
swap( array, i, pos_smallest ) ;
++num_swaps ;
}
}
return num_swaps ;
}
int main()
{
int arr[] { 12, 12, 12, 18, 18, 14, 14, 12, 14, 14, 12, 18, 17, 15, 12, 18 } ;
const int array_size = sizeof(arr)/sizeof( arr[0] ) ;
const int nswaps = selection_sort( arr, array_size ) ;
for( int v : arr ) std::cout << v << ' ' ;
std::cout << "\n#items: " << array_size << " #swaps: " << nswaps << '\n' ; ;
}
|