fork download
  1. #include <iostream>
  2.  
  3. void swap( int& a, int& b ) { int temp = a ; a = b ; b = temp ; }
  4.  
  5. void sort( int a[], std::size_t n )
  6. {
  7. for( std::size_t i = 0 ; i < n ; ++i )
  8. for( std::size_t j = i+1 ; j < n ; ++j )
  9. if( a[j] < a[i] ) swap( a[j], a[i] ) ;
  10. }
  11.  
  12. void print( const int a[], std::size_t n, std::size_t pos_acive )
  13. {
  14. std::cout << "{ " ;
  15. for( std::size_t i = 0 ; i < n ; ++i )
  16. if( i == pos_acive ) std::cout << '[' << a[i] << "] " ;
  17. else std::cout << a[i] << ' ' ;
  18. std::cout << "}\n\nActive Item: " << pos_acive << "\n\n\n" ;
  19. }
  20.  
  21.  
  22. int main()
  23. {
  24. int a[] = { -5, 16, 8, 9, -12, 0, -3, 65, 10, -3, 1 } ;
  25. const std::size_t N = sizeof(a) / sizeof(*a) ;
  26. std::size_t pos_acive = 2 ;
  27. print( a, N, pos_acive ) ;
  28.  
  29. ::swap( a[0], a[pos_acive] ) ; // swap active item with the first element
  30. ::sort( a+1, N-1 ) ; // sort from the second item onwards
  31. // bring the active item into place
  32. std::size_t i = 1 ;
  33. for( ; a[i] < a[i-1] && i < N ; ++i ) std::swap( a[i], a[i-1] ) ;
  34. pos_acive = i-1 ;
  35.  
  36. ::print( a, N, pos_acive ) ;
  37. }
  38.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
{ -5 16 [8] 9 -12 0 -3 65 10 -3 1 }

Active Item: 2


{ -12 -5 -3 -3 0 1 [8] 9 10 16 65 }

Active Item: 6