Monday 6 August 2012

How to implement bubble sort in C++


Program to implement Bubble sort



#include<iostream>

#include<conio.h>

using namespace std;

int main()
{
       int numbers[8], temp = 0, counter = 0, inter = 0;

       cout << "\n\n\t\t\t  __ Bubble Sort __";
      
       for(counter = 0 ; counter < 8; counter++)
       {
              cout << "\n\n\t\t" << counter + 1 << " Number  -  ";

              cin >> numbers[counter];
       }


       for(counter = 8 ; counter >= 1; counter--)
       {
              for(temp = 0; temp <= counter - 2; temp++)
              {
                     if (numbers[temp] > numbers[temp + 1])   
                     //___ if adjacent numbers are in incorrct order __
                     {
                           inter = numbers[temp];

                           numbers[temp] = numbers[temp + 1];  
                           //___ Swap the numbers ___

                           numbers[temp + 1] = inter;
                     }
                     else
                     {
                           continue;
                     }
              }
       }

       cout << "\n\n\t\tSorted List  -  ";

       for(counter = 0 ; counter < 8; counter++)
       {
              cout <<numbers[counter] << " , ";
       }

       cout << "\b\b  ";

       getch();

       return 0;

}


Bubble Sort is a simple sorting algorithm that works by repeatedly going through a list of data items to be sorted comparing each pair of adjacent items and swapping them if they are in the incorrect order. The passes are repeated until no swap is being made. It's a comparison sort. 

Note - Bubble Sort is not a practical sorting algorithm when n is large.
Figure - Bubble Sort Demonstration
  • An example on bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.

No comments:

Post a Comment