Date: 07/04/2025
8. C++ Program to sort elements in ascending order using bubble sort.
#include<iostream>
using namespace std;
int main()
{
int a[20],i,j,n,temp;
cout<<"Enter the size of the array:\n";
cin>>n;
cout<<"Enter the elements:\n";
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"The elements are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
for(i=0;i<n;i++){
for(j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
cout<<"\nElements after bubble sort are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
return 0;
}
Date: 07/04/2025
9. C++ Program to sort elements in ascending order using selection sort.
#include<iostream>
using namespace std;
int main(){
int a[20],i,j,n,temp;
cout<<"Enter the size of the array:\n";
cin>>n;
cout<<"Enter the elements:\n";
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"The elements are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"\nThe elements after sorting are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
return 0;
}
Date: 07/04/2025
10. C++ Program to sort elements in ascending order using insertion sort.
#include<iostream>
using namespace std;
int main()
{
int a[20],i,j,n,temp;
cout<<"Enter the size of the array:\n";
cin>>n;
cout<<"Enter the elements:\n";
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"The elements are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
for(i=0;i<n;i++){
temp=a[i];
j=i-1;
while(j>=0&&a[j]>temp){
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
cout<<"\nElements after bubble sort are:\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\t";
}
return 0;
}