Bubble Sort in C++
Theory
Bubble sort is the most simple type of sort that you can think when performing the sort operation. The first element gets compared with the adjacent element and then swapped(increasing or decreasing depending on user's choice) with the adjacent element and this is done until it finds the right place for the element. This goes on till every element gets sorted.
Time Complexity: n^2(Worst and average)
Program:
int i, j, n, temp;
cin>>n;
int a[n];
for(i=0; i<n; i++)
{
cin>>a[i];
}
for(i=0; i<n-1; i++)
{
for(j=0; j<n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp; //Can also be done by reference
}
} //End of j-for loop
} //End of i-for loop
for(i=0; i<n; i++)
{
cout<<a[i]<<" ";
}
Input:
5
10 2 8 7 3
Output:
2 3 7 8 10