Write a Program to Sort a Set of Strings in Alphabetical Order

Introduction

Very often it was asked in interviews to write down a C program to sort series of strings in alphabetical order. Here we will see the how to do this by writing a c program and also we will see the out puts.

Alphabetical Sorting in C:

Alphabetical sort is a program where character strings are sorted on the basis of the position of characters.

Example:
Lets say you have the below strings and you are asked to sort them alphabetically.

"America",
"Jamaica",
"India",
"Australia",
"Pakistan",
"Germany"

Now the sorted list of strings will be

"America",
"Australia",
"Germany"
"India",
"Jamaica",
"Pakistan",

See the program below.

Find The Code Here


#include <stdio.h>
#include <string.h>
void main()
{
   char name[10][8], tname[10][8], temp[8];
   int i, j, n;
  
   printf("Enter the value of n \n");   
    scanf("%d", &n);
      printf("-----------------------");
      printf("Enter %d names ", n);
   printf("-----------------------");
   
   for (i = 0; i < n; i++)
   {
       scanf("%s", name[i]);
       strcpy(tname[i], name[i]);
   }

   for (i = 0; i < n - 1 ; i++)
   {
       for (j = i + 1; j < n; j++)
       {
           if (strcmp(name[i], name[j]) > 0)
           {
               strcpy(temp, name[i]);
               strcpy(name[i], name[j]);
               strcpy(name[j], temp);
           }
       }
   }

   printf("\n----------------------------------------\n");
   printf("Input Names\tSorted Names\n");
   printf("------------------------------------------\n");
  
   for (i = 0; i < n; i++)
   {
       ("%s\t\t%s\n", tname[i], name[i]);
   }
  
   printf("------------------------------------------\n");
   getch();
}

InPut

Enter the value of n  
6
-----------------------    
Enter 6 names 
-----------------------  
America 
Jamaica 
India 
Australia 
Pakistan 
Germany 

Output

-----------------------   
Input Names   Sorted Names
----------------------- 
America            America         
Jamaica            Australia
India                 Germany
Australia           India
Pakistan           Jamaica
Germany          Pakistan

Happy Coding...

No comments:

Post a Comment