Wednesday, 15 February 2017

Implementation of Bubble Sort Algorithm in C++

The most simplest sorting algorithm is Bubble sort Algorithm. This is an comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Note:-
This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items.

ALGORITHM :

Set i:=1
For i=1 to i<= n-1:
         For j=1 to j<=n-1-i
                   If arr[j]>arr[j+1]
                             Set swap:=arr[j]
                                    arr[j]=arr[j+1];
                                    arr[j+1]=swap
                   End If 
         End For
End For
Exit

PROGRAM:
 
#include <stdio.h>
#define MAX 100

class BubbleSort
{
	 private:
	     int arr[100],n;
	 public:
	     void get_data();
	     void sort();
	     void print();
};
void BubbleSort::get_data()
{
	  printf("\nEnter the total number of elements: ");
	  scanf("%d",&n);
	  printf("\nEnter the elements of the array: \n");
	  for(int i=0;i<n;i++)
	  {
	       scanf("%d",&arr[i]);
	  }
}
void BubbleSort::sort()
{
	  for(int i=0;i<n-1;i++)
	  {
	       for(int j=0;j<n-i-1;j++)
	       {
	             if(arr[j]>arr[j+1])
	             {
	                   int swap=arr[j];
	                   arr[j]=arr[j+1];
	                   arr[j+1]=swap;
	             }
	       }
	  }
}
void BubbleSort::print()
{
	  printf("\nThe updated array is: \n");
	  for(int i=0;i<n;i++)
	  {
	        printf("%d ",arr[i]);
	  }
}
int main()
{
	  BubbleSort bs;
	  bs.get_data();
	  bs.print();
	  bs.sort();
	  bs.print();
	  return 0;
}

OUTPUT:

 


EmoticonEmoticon