Here is a C++ program to sort list of names in ascending order and descending order.
C++ program to sort list of names in ascending order
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char *str[10],*temp;
int n,cmp;
cout<<"How many names to be entered : ";
cin>>n;
cout<<"Enter names : ";
for(int i=0;i<n;i++)
{
str[i]=new char[20];
cin>>str[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
cmp=strcmp(str[j],str[j+1]);
if(cmp>0)
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
cout<<endl<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<endl<<i+1<<".) "<<str[i];
return 0;
}
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhes6v46L62KRhVW4s4q-YmPdTWRtVaigE6BtKQoGNqGrDpIDiSKChe-t-t5ajdMjHKkSBlr3Rht09c56OfXM5XRv4gKxnTGDSxcnXM06Fo0ceGSAGS58UyeAe_j__b5mwJUkGryR0ZVngO/s1600/Capture326.PNG)
#include<string.h>
using namespace std;
int main()
{
char *str[10],*temp;
int n,cmp;
cout<<"How many names to be entered : ";
cin>>n;
cout<<"Enter names : ";
for(int i=0;i<n;i++)
{
str[i]=new char[20];
cin>>str[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
cmp=strcmp(str[j],str[j+1]);
if(cmp>0)
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
cout<<endl<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<endl<<i+1<<".) "<<str[i];
return 0;
}
OUTPUT
C++ program to sort list of names in descending order
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char *str[10],*temp;
int n,cmp;
cout<<"How many names to be entered : ";
cin>>n;
cout<<"Enter names : ";
for(int i=0;i<n;i++)
{
str[i]=new char[20];
cin>>str[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
cmp=strcmp(str[j],str[j+1]);
if(cmp<0)
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
cout<<endl<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<endl<<i+1<<".) "<<str[i];
return 0;
}
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQnONOU95rowof5kpZipPLuDzrwvAWcGAZ-nyHsCXUY6PVzY-RBBSQKp9ZoIWnwixTqarAGjfAVcKOEBVRWO_xalw8JOr5VyLuRq3bir6HAFymvwGpa_B2i0NpIpA1QhM2iifKj0M3T92X/s1600/Capture328.PNG)
#include<string.h>
using namespace std;
int main()
{
char *str[10],*temp;
int n,cmp;
cout<<"How many names to be entered : ";
cin>>n;
cout<<"Enter names : ";
for(int i=0;i<n;i++)
{
str[i]=new char[20];
cin>>str[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
cmp=strcmp(str[j],str[j+1]);
if(cmp<0)
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
cout<<endl<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<endl<<i+1<<".) "<<str[i];
return 0;
}
No comments:
Post a Comment