Bubble Sort in C++

C++ Program to implement Bubble Sort. Sinking sort is the another name of Bubble sort. This algorithm repeatedly iterates through the array, compares each pair of adjacent elements and swaps them if the 1st element is larger than 2nd.

Source code :

#include <iostream>

using namespace std;

int main(){

int array[] = {1,45,10,35,100,13,147,500,80};
int size = sizeof(array)/sizeof(array[0]);

int i,j,min;

for (i = 0; i < size ; i++){
    
    for(j = 0  ; j < size - i ; j++){
        
        if(array[j] > array[j+1]){
            
            min = array[j];
            array[j] = array[j+1];
            array[j+1] = min;
            
        }
    }
    
}


for(i = 0 ; i < size ; i++){
    cout<<array[i]<<endl;
}


return 0;

}




Output :

1
10
13
35
45
80
100
147
500

Notes :

Algorithm

  1. Compare 1st and 2nd elements in the Array
  2. If 1st larger than 2nd element, perform swap
  3. Now compare 2nd and 3rd, and swap if the 2nd element is larger than 3rd
  4. Repeat the steps untill you reach the last element
  5. Now the Array will be sorted

Since this Algorithm is bubbling the smallest element to the starting of the Array it was named as Bubble Sort.


Output :


                

Comments :