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/ex6.1/bubble_sort_int.cpp

130 lines
2.0 KiB
C++

/*
* Bubble sort some lists by exploiting templates
*
*/
#include <iostream>
#include <cstring>
#define LIST_SIZE 10
template<class T>
void display( T t[], int n );
template<class T>
void sort( T* A, const int size );
template<class T>
void order( T& a, T& b );
int main() {
int list[LIST_SIZE] = { 2295, 14500, 9127, 23079, 20612, 5571, 21959, 10032, 18339, 16673 };
float flist[LIST_SIZE] = { 835.2, 3248.8, 0.1213123, 8.234234, 8242.25823, 802348234.8, .9123812414, 0.00000001, 842, 10000000 };
const char* clist[LIST_SIZE] = {
"b",
"cccccccccc",
"aaabcd",
"axefsaf",
"poqkud",
"6xnj439yu",
"nullieksj",
"bell",
"uuisdjk",
"aaaaaaa",
};
// Print the original
std::cout << "Original: ";
display(list, LIST_SIZE);
std::cout << std::endl;
// sort it
sort( list, LIST_SIZE );
// Print it
std::cout << "Sorted: ";
display(list, LIST_SIZE);
std::cout << std::endl;
// Doing Floats
// Print the original
std::cout << "Original: ";
display(flist, LIST_SIZE);
std::cout << std::endl;
// sort it
sort( flist, LIST_SIZE );
// Print it
std::cout << "Sorted: ";
display(flist, LIST_SIZE);
std::cout << std::endl;
// Doing Chars
// Print the original
std::cout << "Original: ";
display(clist, LIST_SIZE);
std::cout << std::endl;
// sort it
sort( clist, LIST_SIZE );
// Print it
std::cout << "Sorted: ";
display(clist, LIST_SIZE);
std::cout << std::endl;
return 0;
}
template<class T>
void display( T t[], int n) {
for( int i = 0; i < n ; i++ )
{
if ( i != 0 )
{
std::cout << ", ";
}
std::cout << t[i];
}
}
template<class T>
void sort( T* A, const int size ) {
for (int i = 0 ; i < size ; i++ ) {
for (int j = 0 ; j < size - 1 ; j++) {
order( A[ i ], A[ j ] );
}
}
}
template<class T>
void order( T& a, T& b ) {
// b is greater or equal to a, do nothing
if ( a < b ) {
return;
}
T tmp = a;
a = b;
b = tmp;
}
template<>
void order( const char* &a, const char* &b ) {
if ( strcmp(a, b) <= 0 ) {
return ;
}
const char* tmp = a;
a = b;
b = tmp;
}