1
0
Fork 0
This repository has been archived on 2021-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
uni-m.cds-adv-prog/ex2/ex2.1/bubble_sort_int.cpp
2019-11-26 10:55:12 +01:00

90 lines
1.4 KiB
C++

/*
* Bubble sort a list of 10 integers
*
* I'd rather have the method without pointers.
* As a user of the function, I don't have to think about passing pointers, which is also nice
*/
#include <iostream>
#define LIST_SIZE 10
#define USE_PTR 1
void sort( int* A, const int size );
#if !USE_PTR
void order( int& a, int& b );
#else
void orderptr( int* a, int* b );
#endif
int main() {
int list[LIST_SIZE] = { 2295, 14500, 9127, 23079, 20612, 5571, 21959, 10032, 18339, 16673 };
// Print the original
std::cout << "Original: ";
for( int i = 0; i < LIST_SIZE ; i++ )
{
if ( i != 0 )
{
std::cout << ", ";
}
std::cout << list[i];
}
std::cout << std::endl;
// sort it
sort( list, LIST_SIZE );
// Print it
std::cout << "Sorted: ";
for( int i = 0; i < LIST_SIZE ; i++ )
{
if ( i != 0 )
{
std::cout << ", ";
}
std::cout << list[i];
}
std::cout << std::endl;
return 0;
}
void sort( int* A, const int size ) {
for (int i = 0 ; i < size ; i++ ) {
for (int j = 0 ; j < size - 1 ; j++) {
#if !USE_PTR
order( A[ i ], A[ j ] );
#else
orderptr( &A[ i ], &A[ j ] );
#endif
}
}
}
#if !USE_PTR
void order( int& a, int& b ) {
// b is greater or equal to a, do nothing
if ( a < b ) {
return;
}
int tmp = a;
a = b;
b = tmp;
}
#else
void orderptr( int* a, int* b ) {
if ( *a < *b ) {
return;
}
int* tmp = a;
a = b;
b = tmp;
}
#endif