8
Bubble
- #include <iostream>
- using namespace std;
- typedef float List[];
- static void print( List tab, const int siz )
- {
- for ( int i=0; i < siz; i++ )
- cout << tab[ i ] << ((i < siz-1) ? ", " : "\n");
- }
- inline void swap( float &x, float &y )
- {
- float t = x;
- x = y;
- y = t;
- }
- void sort( List tab, const int siz )
- { // bubble sort
- for ( int i=siz-1; i > 0; i-- ) {
- print( tab, siz );
- for ( int j=0; j < i; j++ )
- if ( tab[j] > tab[j+1] )
- swap( tab[j], tab[j+1] );
- }
- }
- int main() {
- List tab = { 55.55, 22.22, 99.99, 66.66, 44.44, 88.88, 33.33, 77.77 };
- int siz = sizeof (tab) / sizeof (float);
- cout << "Sorting " << siz << " floats:\n";
- sort( tab, siz );
- print( tab, siz );
- }
- #include <iostream>
- #include <string>
- using namespace std;
- template <class T>
- static void print( T tab[], const int siz )
- {
- for ( int i=0; i < siz; i++ )
- cout << tab[ i ] << ((i < siz-1) ? ", " : "\n");
- }
- template <class T>
- void sort( T tab[], const int siz )
- { // bubble sort
- T t;
- for ( int i=siz-1; i > 0; i-- )
- for ( int j=0; j < i; j++ )
- if ( tab[j] > tab[j+1] ) {
- T t = tab[j];
- tab[j] = tab[j+1];
- tab[j+1] = t;
- }
- }
- int main() {
- int siz;
- float tabi[] = { 55, 22, 99, 66, 44, 88, 33, 77 };
- siz = sizeof (tabi) / sizeof (int);
- cout << "Sorting " << siz << " integers:\n";
- sort( tabi, siz );
- print( tabi, siz );
- float tabf[] = { 55.55, 22.22, 99.99, 66.66, 44.44, 88.88, 33.33, 77.77 };
- siz = sizeof (tabf) / sizeof (float);
- cout << "Sorting " << siz << " floats:\n";
- sort( tabf, siz );
- print( tabf, siz );
- string tabs[10] = { "T", "a", "f", "Z", "F", "Q", "z", "q", "t", "A" };
- siz = sizeof (tabs) / sizeof (string);
- cout << "Sorting " << siz << " strings:\n";
- sort( tabs, siz );
- print( tabs, siz );
- }
Comments