Bubble sort in C++
#include<iostream> //header file
using namespace std; //header file
int main() //main function
{
int i,j,temp=0,n,a[20]; //declaration and initialization of variables
cout<<"Enter the array size : \n"; //prints the msg on output screen
cin>>n; //stores value in variable n
cout<<"\nEnter the array element:\n"; //prints the msg on output screen
for(i=0;i<n;i++) //for loop runs from i=0 to i=n-1
cin>>a[i]; //stores value in a[i]
for(i=0;i<n;i++) //for loop runs from i=0 to i=n-1
{
for(j=0;j<n-i;j++) //for loop runs from j=0 to j=n-i
{
if(a[j]>a[j+1]) //if block
{
temp=a[j]; //storing value of a[j] in temp
a[j]=a[j+i]; //storing value of a[j +1] in a[j]
a[j+1]=temp; //storing value of temp in a[j+1]
}
}
}
cout<<"sorted array:\n"; //prints the msg on output screen
for(i=0;i<n;i++) //for loop runs from i=0 to i=n-1
cout<<"%d\t",a[i];
return 0;
}
Output:
Enter the array size :
3
Enter the array element:
44
33
66
sorted array:
33 44 66
Comments
Post a Comment