Search This Blog

C Program to Sort Strings using Selection Sorting

Here i am writing programs in c and c++ languages to sort a given number of strings. Sorting is carried out based on the ASCII values of the letters in the strings. The string comparing function strcmp() is used in the program. These programs sort a given set of strings in ascending order.To change it into descending order just replace > with < in comparison line. The comparison line in the code is marked by comment.

C Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{

int i,j,n;
char str[20][20],temp[20];
puts("\nEnter the number of strings to be sorted\n");
scanf("%d",&n);
printf("\nEnter the strings one by one\n");
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0) /* Comparison line */
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("\nThe sorted strings:\n");
for(i=0;i<=n;i++)
puts(str[i]);
getch();
}

C++ program:


#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
char str[20][20],temp[20];
cout<<"\nEnter the number of strings to be sorted\n";
cin>>n;
cout<<"\nEnter the strings one by one\n";
for(i=0;i<n;i++)
gets(str[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[i],str[j])>0) /* Comparison line */
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
cout<<"\nThe sorted strings:\n";
for(i=0;i<n;i++)
puts(str[i]);
getch();
}

No comments: