BUBBLE SORT Algorithm and C++ program

In Bubble sort the largest number goes to the last position of the series or array if the sorting is in ascending order.









ALGORITHM

The main logic lies in the following "for loop"

for(int x=0; x<n; x++)

 {

  for(int y=0; y<n-1; y++)

  {

   if(array[y]>array[y+1])

   {

    int temp = array[y+1];

    array[y+1] = array[y];

    array[y] = temp;

   }

  }

 }


First Pass:
5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) \to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )



C++ Program


#include<iostream>
using namespace std;


int main()

{
 const int array_size = 4;
 int x[array_size],  hold;

 for (int i = 0 ; i <= 3 ; i++ )
 cin>>x[i];

 cout<<"\nOriginal Numbers:\n"; 
  for ( i=0; i<=3 ; i++) 
   cout<<x[i]<<"   ";


  //Bubble Sorting begins

 for (int passes = 0;  passes < array_size - 1;  passes++)
 {
  for (int j = 0;  j < array_size - passes - 1;  j++)
  {
   if (x[j] > x[j+1])
   {
    hold = x[j];
    x[j] = x[j+1];
    x[j+1]=hold;

   }
  }
 } 


 //Bubble Sorting finished

 cout<< "\nAscending Order:\n"; //Printing Numbers in Ascending order.

 for (i = 0; i<4 ; i++) //Printing
  cout<< x[i]<<"   ";
 cout<<endl<<endl;
 return 0;
}




source:wikipedia.com 

No comments:

Post a Comment