Bubble Sort Program in C++ Using Array

Bubble sort program in c++ sorting program to sort the numbers. Bubble sorting is the important sorting method and most used sorting method in c++.

#include<iostream>
using namespace std;
int main()
{
int a[20],n,i,j,temp;
cout<<"Enter the size";
cin>>n;
cout<<"Enter the elements"; 
for(i=0;i<n;++i)
cin>>a[i];
for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
cout<<"After sorting";
for(i=0;i<n;++i)
cout<<" "<<a[i];
return 0;
}

 

Output:

Enter the size 3

Enter the elements 12 34 56

After sorting 12 34 56

Return Statement in C++ Program

The return statement directs execution away from the current function and toward the function that called it. 

It is possible to return a result return variable as an option. There may be multiple return statements in a function, but they all return the same type.

Temp in C++ Program

Temp is a variable that is used to store temporary data that may be used later in the program execution. 

A temporary variable is a variable in computer programming that has a short lifetime and is used to hold data that will be discarded soon or before it can be stored in a more permanent memory location.

For Loop in C++

A for loop is a repetition control structure that lets you design a loop that needs to run a certain number of times quickly. 

A for-loop, or simply for loop, is a control flow statement in computer science that specifies iteration and allows code to be executed repeatedly. 

While-loops increment and test a loop variable, for-loops can be regarded of as short hands for while-loops. Using this program we can execute bubble sort program in c++.