Alphabetizing a string array

May 1, 2013 at 12:27am
My array will contain first and last names. How do i alphabetize the names inside?

for instance names Dan Andrew Drew Vincent will be organize as such:

arr[0] Andrew, arr[1] Dan, arr[2] Drew, arr[3] Vincent..

i am currently looking at function isalpha() // is the parameter alphabetic(A..Z)

but i am puzzled at how to incorporate it into a reasonable control structure... perhaps a for loop iteration somehow involving this function?

anyway any help would be appreciated.
May 1, 2013 at 12:31am
Show us what you have so far, so we can now where to go from
May 1, 2013 at 12:32am
Well most names are only letters you could probably sort by the first few characters by turning the char to an int eg (int)'a' or try to use a map
May 1, 2013 at 12:34am
Oh you can also try std::sort migyt be easiest
May 1, 2013 at 12:40am
Ssturges:

I dont have anything so far i am still trying to figure out the pseudo code.
May 1, 2013 at 1:55am
bump

does anyone have any other suggestions?
May 1, 2013 at 2:18am
Yes, I have one lol

So, I don't know how to explain it, so I wrote out the code, but what I have will only check for the first two letters, so for example, it will catch Dan and Drew, but not Dan and Daniel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>

using namespace std;

int main(){
string names[]={"Drew","Andrew","Dan","Vincent"};
string temp="";
int arrSize = sizeof(names)/sizeof(names[0]);

cout << "The following is a list of names unorganized:\n";
for(int s = 0; s < arrSize; s++)
    cout << names[s]<<" ";

for (int x = 0; x < arrSize; x++){
        for(int y = 0; y < arrSize-1; y++){
            if (names[x].at(0) < names[y].at(0)){
                    temp = names[x];
                    names[x] = names[y];
                    names[y] = temp;
            }
            else if (names[x].at(0) == names[y].at(0))
                if (names[x].at(1) < names[y].at(1)){
                        temp = names[x];
                        names[x] = names[y];
                        names[y] = temp;
                }
        }
}

cout << "\n\n\nThe following is a list of names organized:\n";
for(int s = 0; s < arrSize; s++)
    cout << names[s]<<" ";

cout << endl << endl;

return 0;
}


Like I said this is just a rough draft, and will only check the first two letters. Once you understand whats going on, it shouldn't be too hard to make it check every letter for a particular string.
Last edited on May 1, 2013 at 2:18am
Topic archived. No new replies allowed.