Bubble Sort Algorithm

Posted by Tully on Wed 30 June 2010

I was just reading about sorting arrays in C++ and came across the bubble sort.

bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Wikipedia

Bubble Sort Algorithm in C++

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int num[ 10 ] = { 0, 2 ,1 ,55 ,22, 77, 32, 22, 77, 99 };
    int numSize = 10;
    int temp;

    cout << "Before the sort!" << endl;

    for (int i = 0; i < numSize; i++)
        cout << setw(5) << num[i];
        cout << "\n\n";

        for(int i=0; i < numSize; i++)
        {
            for (int j = 0; j < numSize; j++)
            {
                if (num[i] < num[j])
                {
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }

    cout << "After the sort!" << endl;

    for (int i = 0; i < numSize; i++)
        cout << setw(5) << num[i];
        return 0;
}