In Bubble sort, two consecutive elements in a given list are compared and their positions in the given list (array) are interchanged in ascending or descending order as desired. Consider the following series of numbers, which are to be arranged in ascending or descending order. The series of numbers to be arranged are presented in the form of an array. The input array has the following form:
s[0]
.
.
.
.
.
s[n-l]
The process of sequentially visiting all or some of the elements is called a pass. In Bubble sort, arranging n elements requires (n-1) passes. In case the numbers are to be arranged in ascending order, at the end of one pass, the largest number is moved to the last position i.e. bubbles up the largest number. Taking this as the new series and excluding the largest number repeat the process until all the numbers in the series are arranged in ascending order. The Bubble sort is also given the name Interchange or Sinking sort.
Example
C++ program illustrates sorting 5 numbers in ascending order using Bubble sort.
#include <iostream.h>
void main(void)
{
int t,i,j;
int n;
cout<<"Enter the number of values to be sorted ";
cin>>n;
int s[20];
cout<<"\nEnter the values ";
for(i=0;i<n;i++)
cin>>s[i];
cout<<endl;
cout<<"The list to be sorted is ";
for(i=0;i<n;i++)
cout<<s[i]<<" ";
for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if (s[j]>s[j+1])
{
t=s[j+1];
s[j+1]=s[j];
s[j]=t;
}
}
cout<<endl;
cout<<"Pass "<<i+1<<" ";
for(int k=0;k<n;k++)
cout<<s[k]<<" ";
}
cout<<endl;
}
Input and Output:
Enter the number of values to be sorted 5
Enter the values 34 22 49 10 67
The list to be sorted is 342249 1067
Pass 1:2234 104967
Pass 2:22 10344967
Pass 3:10 22 34 49 67
Pass 4:10 22 34 49 67
Pass 5:10 22 34 49 67
Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Related Articles
Basic Courses
Advance Courses