C++ program to sort n strings

 This C++ program sorts n strings using pointer. The value for n is read as input and the strings are read into the 2D character array a[][]. A pointer array p[] is declared to store the address of each element in the array a[][]. Then the program uses nested for loop to sort the strings. Here strcmp() function is used to compare each strings and strcpy() function is used to copy the strings from one location to another.After sorting is completed, the program displays the sorted strings to the output screen.

Program


#include<iostream.h>

#include<conio.h>

#include<string.h>

void main()

{

          char a[10][20],*p[10],temp[20];

          int n,i,j;

          cout<<"Enter the value for n: ";

          cin>>n;

          cout<<"\nEnter the strings:\n\n";

          for(i=0;i<n;i++)

          {

                   cin>>a[i];

                   p[i]=a[i];

          }

          for(i=0;i<n-1;i++)

                   {

                             for(j=0;j<n-i-1;j++)



                             {

                                      if(strcmp(p[j],p[j+1])>0)

                                                {

                                                          strcpy(temp,p[j]);

                                                          strcpy(p[j],p[j+1]);

                                                          strcpy(p[j+1],temp);

                                                }

                             }

                    }

                   cout<<"Strings after sorting: \n";

                   for(i=0;i<n;i++)

                   {

                             cout<<"\n"<<p[i];

                   }

          getch();

}

No comments: