Bubble sorting
#include <iostream>
using namespace std;
int main()
{
int a[20],i,n,j,temp;
cout<<"enter the number of elements in the
array"<<endl;
cin>>n;
cout<<"enter the elements"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
temp=0;
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
cout<<"the sorted elements are "<<endl;
for(i=0;i<n;i++)
{
cout<<a[i];
cout<<'\t';
}
return 0;
}
Selection sort
#include <iostream>
using namespace std;
int main()
{
int a[20],i,n,j,temp,temp1,s;
cout<<"enter the number of elements in the
array"<<endl;
cin>>n;
cout<<"enter the elements"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
temp=a[i];
s=i;
for(j=i+1;j<n;j++)
{
if(temp>a[j])
{
temp=a[j];
s=j;
}
}
temp1=a[i];
a[i]=a[s];
a[s]=temp1;
}
cout<<"the sorted elements are"<<endl;
for(i=0;i<n;i++)
{
cout<<a[i];
cout<<'\n';
}
return 0;
}
Insertion sorting
#include<iostream>
using namespace std;
int main()
{
int
n, a[50], i, j, temp;
cout<<"Enter
the no. of elements in the array";
cin>>n;
cout<<"Enter
the elements ";
for(i=0;
i<n; i++)
{
cin>>a[i];
}
for(i=1;
i<n; i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])
&& (j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
cout<<"sorted
elements \n";
for(i=0;
i<n; i++)
{
cout<<a[i]<<"
";
}
return 0;
}
Merge sorting
#include <iostream>
using namespace std;
int a[50];
void merge(int,int,int);
void mergesort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int
high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
int n,i;
cout<<"enter the number of
elements"<<endl;
cin>>n;
cout<<"enter the
elements"<<endl;
for(i=1;i<=n;i++)
{
cin>>a[i] ;
}
mergesort(1,n);
cout<<"Sorted
elements"<<endl;
for(i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
Comments
Post a Comment