Search code examples
c++stringsortingalphabetical

How to alphabetically sort strings?


I have been trying to use this c++ program to sort 5 names alphabetically:

#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;

int main()
{
char names[5][100];
int x,y,z;

char exchange[100];

cout << "Enter five names...\n";

for(x=1;x<=5;x++)
{
    cout << x << ". ";
    cin >> names[x-1];
}
getch();

for(x=0;x<=5-2;x++)
{
    for(y=0;y<=5-2;y++)
    {
        for(z=0;z<=99;z++)
        {
            if(int(names[y][z])>int(names[y+1][z]))
            {   
                strcpy(exchange,names[y]);
                strcpy(names[y],names[y+1]);
                strcpy(names[y+1],exchange);
                break;
            }
        }   
    }
}   

for(x=0;x<=5-1;x++)
    cout << names[x];

return 0;
}

If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:

AndyEarlDonChrisBill

Could someone please tell me whats wrong with my program?


Solution

  • You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).

    #include <iostream>
    #include <set>
    #include <algorithm>
    
    void print(const std::string& item)
    {
        std::cout << item << std::endl;
    }
    
    int main()
    {
        std::set<std::string> sortedItems;
    
        for(int i = 1; i <= 5; ++i)
        {
            std::string name;
            std::cout << i << ". ";
            std::cin >> name;
    
            sortedItems.insert(name);
        }
    
        std::for_each(sortedItems.begin(), sortedItems.end(), &print);
        return 0;
    }
    

    input:

    1. Gerardo
    2. Carlos
    3. Kamilo
    4. Angel
    5. Bosco

    output:

    Angel
    Bosco
    Carlos
    Gerardo
    Kamilo