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
|
#include <iostream>
void swap( int& a, int& b ) { int temp = a ; a = b ; b = temp ; }
void sort( int a[], std::size_t n )
{
for( std::size_t i = 0 ; i < n ; ++i )
for( std::size_t j = i+1 ; j < n ; ++j )
if( a[j] < a[i] ) swap( a[j], a[i] ) ;
}
void print( const int a[], std::size_t n, std::size_t pos_acive )
{
std::cout << "{ " ;
for( std::size_t i = 0 ; i < n ; ++i )
if( i == pos_acive ) std::cout << '[' << a[i] << "] " ;
else std::cout << a[i] << ' ' ;
std::cout << "}\n\nActive Item: " << pos_acive << "\n\n\n" ;
}
int main()
{
int a[] = { -5, 16, 8, 9, -12, 0, -3, 65, 10, -3, 1 } ;
const std::size_t N = sizeof(a) / sizeof(*a) ;
std::size_t pos_acive = 2 ;
print( a, N, pos_acive ) ;
::swap( a[0], a[pos_acive] ) ; // swap active item with the first element
::sort( a+1, N-1 ) ; // sort from the second item onwards
// bring the active item into place
std::size_t i = 1 ;
for( ; a[i] < a[i-1] && i < N ; ++i ) std::swap( a[i], a[i-1] ) ;
pos_acive = i-1 ;
::print( a, N, pos_acive ) ;
}
|