Bubble Sort Algorithm in C++

Bubble Sort Algorithm

        In the bubble sort algorithm, the biggest element is bubbled at the end of the array. 

        The algorithm has two loops first one to go through the array normally and the second one will be used for comparison of two array elements and swapping. 

        In the second loop, each array element will be compared to the next one, and if the next element is smaller than the current element they will be swapped. This will be repeated for all the array elements with the help of the first loop.

        In the end, the array will be sorted. Print the array!

Code

#include <bits/stdc++.h>

using namespace std;


int main() 

{

    int a[5]={500,3,45,999,78};             //array

    

    for(int i=0;i<4;i++)        // always iterate the loop one less than the array size 

    {     

        for(int j=0;j<4-i;j++)              // second loop will go till (size - 1)-i

        {

            if(a[j]>a[j+1])             // if element is larger swap it

            {

             int t=a[j];                  //

             a[j]=a[j+1];            // swapping section 

             a[j+1]=t;              //

            }

        }

    }

    

    for(int i=0;i<5;i++)                    // print the array

    { 

        cout<<a[i]<<" ";

        

    }

    

    return 0;

}


Output

3 45 78 500 999 


Post a Comment

0 Comments