Quick actions

cmd+k|ctrl+k

Navigation

Languages

Bubble Sort

Snippet info

Language

Cpp

Visibility

public

Author

algoll

Created

2015-08-30T14:17:15Z

Updated

2015-08-31T08:05:15Z

#include <iostream>
#include <ctime>
#include <cstdlib>

using std::cout;
using std::endl;

template <typename T>
void bubbleSort(T * arr, const std::size_t size) {
    for(std::size_t i(0); i < size - 1; ++i) {
        for(std::size_t j(0); j < size - i - 1; ++j) {
            if(arr[j] > arr[j + 1])
                std::swap(arr[j], arr[j + 1]);
        }
    }
}

inline void initArray(int * arr, const std::size_t size) {
    srand(time(0));
    
    for(std::size_t i(0); i < size; ++i) {
        arr[i] = rand() % 100 + 1; // [0:99]
    }
}

inline void show(int * arr, const std::size_t size) {
    for(std::size_t i(0); i < size; ++i) {
        cout << arr[i];
        
        if(i >= size - 1)
            cout << ";";
        else
            cout << ", ";
    }
    cout << endl;
}

int main() {
    static const std::size_t size = 10;
    int myArray[size];
    
    initArray(myArray, size);
    show(myArray, size); // unsorted
    
    bubbleSort(myArray, size);
    
    show(myArray, size); // sorted
    
    return 0; // ~ EXIT_SUCCESS
}
INFO