Bubble Sort

This is a brute force method of sorting.  Compare the successive elements from position 1 to last. This is one
iteration. Do till (n-1) times.

5 4 3 2 1
4 5 3 2 1
4 3 5 2 1
4 3 2 5 1
4 3 2 1 5
This is iteration1. So at the end, maximum element moves to the end.

The time complexity of this algorithm is O(n*n).


 void bubble_sort(int unsorted[],int n)
 {
     int temp;
    for(int i=0;i<number_of_elements-1;i++)
    {
       for(int j=0;j<number_of_elements-i-1;j++)
       {
            if(unsorted[j]>unsorted[j+1])
             {
                 temp=unsorted[j];
                 unsorted[j]=unsorted[j+1];
                 unsorted[j+1]=temp;
             }
        }
     }

Complete implementation can be found at https://github.com/sowmyaravidas/Sorting-Algorithms

Advertisements

Tagged: ,

One thought on “Bubble Sort

  1. […] 5 4 3 2 1 1 4 3 2 5 1 2 3 4 5 1 2 3 4 5 Well, the time complexity is O(n*n) which is same as https://sowmyaravidas.wordpress.com/2012/10/06/bubble-sort/ […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s