Software & Finance





C++ - Sorting Strings





C++ program for sorting string in ascending order is given on this page. This program will accept the number of elements as first input. Then it will use the for loop to input the elements list.

 

Two nested for loops are used for sorting in ascending order. If you need decending order program, then change the if condition from > to <.

 


Source Code


#include <iostream>

#include <string>

 

// Program for ascending order of String Values

 

int main()

{

    int max;

    std::cout << "\nProgram for Ascending order of String Values";

    std::cout << "\n\nEnter the total number of elements: ";

    std::cin >> max;   

    std::cout << "\n:";

 

    char **strarray = new char*[max];

 

    for(int i = 0; i < max; i++)

    {

        strarray[i] = new char[128];

        std::cout << "Enter [" << i + 1 << "] element: ";

        std::cin >> strarray[i];

    }

 

    for(int i = 0; i < max; i++)

    {

        for(int j = 0; j < max; j++)

        {

            if(strcmp(strarray[i],strarray[j]) < 0)

            {

                char temp[128];

                strcpy(temp, strarray[i]);

                strcpy(strarray[i],strarray[j]);

                strcpy(strarray[j],temp);

            }

        }

    }

 

    std::cout << "\n\nThe strings in ascending orders are given below:\n\n";

    for(int i = 0; i < max; i++)

    {

        std::cout << "Sorted [" << i + 1 << "] element: ";

        std::cout << strarray[i];

        std::cout << "\n";

        delete strarray[i];

    }

 

    delete [] strarray;

    return 0;

}

Output


Program for Ascending order of String Values

 

Enter the total number of elements: 5

 

Enter [1] element: DDD

Enter [2] element: EEE

Enter [3] element: AAA

Enter [4] element: BBB

Enter [5] element: CCC

 

 

The strings in ascending orders are given below:

 

Sorted [1] element: AAA

Sorted [2] element: BBB

Sorted [3] element: CCC

Sorted [4] element: DDD

Sorted [5] element: EEE