Bubble sort

Bubble sort is O(n2) sorting algorithms and it is stable. First step is to compares each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. If swap is occurred repeat step one.

title

In [ ]:
#include <algorithm>
    
    /// ========== Bubble sort ==========
    template<class Iter>
    void bubbleSort(Iter begin, Iter end) {
        bool swapped = false; // set true if it was swap
        auto j = end - 1;
        do {                      
            swapped = false;       
            for (auto i = begin; i != j; ++i) { // loop through from back to forward
                if (*i > *(i + 1)) {            // if actual element greater than the next element, swap them
                    std::swap(*i, *(i + 1)); 
                    swapped = true;             // set swapped true
                }
            }
            --j;
        } while (swapped && j > begin);
    }
    

In the main we generate a test array using C++11 lambda function and random generator engine.

In [ ]:
#include <iostream>
    #include <random>
    #include <functional>
    #include <ctime>
    
    const int n = 10;
    
    ////////// Using random generator engine //////////
    std::default_random_engine gen((unsigned int)std::time(0));
    std::uniform_int_distribution<int> distribution(1, 50);
    auto randInt = std::bind(distribution, gen); // using randInt() generate integer number between (1-50)
    
    template<class Iter>
    void printArray(Iter begin, Iter end) {
        for (auto i = begin; i != end; i++) {
            std::cout << *i << ", ";
        }
        std::cout << std::endl;
    }
    
    template<class Iter>
    void testSorting(int* testArray, void(*sort)(Iter, Iter)) {
        std::cout << "original:  ";
        printArray(testArray, testArray + n);
    
        sort(testArray, testArray + n);
        std::cout << "sorted:  ";
        printArray(testArray, testArray + n);
    }
    
In [ ]:
std::cout << "Testing sort algorithms ...\n\n";
        
    int* test = new int[n];
    
    auto generate = [](decltype(test[0]) i){ i = randInt(); };
    std::for_each (test, test + n, generate);
    
    std::cout << "*** Bubble sort: ***\n";
    testSorting<decltype(test)> (test, bubbleSort);
    std::cout << "\n";
    
    delete[] test;