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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <cstdlib>
#include <ctime>
#include <iostream>
void print_array( const int array[], int size ) ;
void sort_array( int array[], int size ) ;
int main()
{
const int size = 20 ; // size is known at compile time
const int max_v = 100 ;
int array[size] {} ; // initialised to all zeroes (no need for dynamic allocation)
std::srand( std::time(nullptr) );
for( int& v : array ) v = std::rand() % max_v + 1 ;
std::cout << "unsorted array:\n\t" ;
print_array( array, size ) ;
sort_array( array, size ) ;
std::cout << "sorted array:\n\t" ;
print_array( array, size ) ;
}
void print_array( const int array[], int size )
{
if( array == nullptr ) return ;
for( int i = 0 ; i < size ; ++i ) std::cout << array[i] << ' ' ;
std::cout << '\n' ;
}
void swap_items( int array[], int a, int b ) // invariant: valid array, positions a, b
{
const auto temp = array[a] ;
array[a] = array[b] ;
array[b] = temp ;
}
// return true if there was a swap
bool bubble_up( int array[], int size ) // invariant: valid array, size > 1
{
bool swapped = false ;
for( int i = 0; i < (size-1); ++i )
{
if( array[i] > array[i+1] )
{
swap_items( array, i, i+1 ) ;
swapped = true ;
}
}
return swapped ;
}
void sort_array( int array[], int size )
{
if( array == nullptr || size < 2 ) return ;
// keep bubbling up till there are no more swaps
while( bubble_up( array, size ) ) ;
}
|