What is Bubble Sort ?

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
Algorithm

  1. Loop through the whole array starting from index 1
  2. If the number in the array at index i-1 is greater than i, swap the numbers and continue
  3. Once the end of the array is reached, start looping again from the beginning
  4. Once no more elements can be swapped, the sorting is complete

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes

Implementation

Bubble sort works by going through the array multiple times and swapping elements that are out of order as we go through the array. Every pass through the array, we move the largest element to the end.

55,6,21,56,12. ( Swap ) => 55 , 6
6,55,21,56,12. ( Swap ) => 55 , 21
6,21,55,56,12. ( Swap ) => 56 , 12
6,21,55,12,56. ( Swap ) => 55 , 12
6,21,12,55,56. ( Swap ) => 21 , 12
6,12,21,55,56.

Code

// Bubble Sort
#include<iostream.h>
#include<conio.h>
// Display For Array
void display(int number[],int size){
   for(int i=0;i<size;i++){
      cout<<" "<<number[i];
      (size==i+1)? cout<<".": cout<<",";
   }
}
void main(){
   clrscr();
   int size = 8;
   int array[10];
   array[0] = 34;
   array[1] = 304;
   array[2] = 302;
   array[3] = 745;
   array[4] = 91;
   array[5] = 5;
   array[6] = 764;
   array[7] = 200;
   cout<<"\n ------Bubble Sort------ ";
   cout<<"\n Before Sorting \n";
   display(array,size);
   cout<<"\n After Sorting \n";
   //Bubble Sort
   for(int i = size - 1; i >= 0; i--){
      for(int j = 1; j <= i; j++){
         if(array[j-1] > array[j]){
            //Swap
            int temp_A = array[j-1];
            array[j-1] = array[j];
            array[j] = temp_A;
         }
      }
   }
   display(array,size);
   getch();
}

Live Demo
demo

(Visited 216 times, 1 visits today)
Share with Friends :