Search code examples
c++bubble-sort

Sorting a 2D Char Array in Alpha order?


I am trying to sort a 2D array of names into alphabetical order, but I can not seam to get it to work.

I am using a bubble sort on the letters, and this is sorting the 1st letter of the names fine, but 3 of the names start with the same letter and they are still out of order.

I have tried googleing and stuff but every ting says to use vectors or string variables.. but I am limited to using 2d char arrays..

Any ideas?

Here is the code I have at the moment that works nearly:

using namespace std;

int main (){

    char heroes[11][17] = { "Captain America", "Thor", "Wolverine", "Cyclops", "Goliath", "Beast", "Angel", "Colossus", "Hulk", "Quicksilver", "Ironman"};

    cout<<"Printing the array as is"<<endl<<endl;

    for (int i=0; i<12; i++){
        cout<<heroes[i]<<endl;
    }

    cout<<endl<<"Ordering the heroes in Alphabetical order"<<endl<<endl;

    char temp = NULL;
    // bubble sort
    for(int i=0;i<11;i++){
        for(int j=0; j<(11-1); j++){
            if (heroes[i][0] < heroes[j][0]){
                for (int k=0; k<17-1; k++){
                    swap(heroes[i][k], heroes[j][k]);
                }
            }
        }
    }

    cout<<"Printing the array Sorted"<<endl<<endl;

    for (int i=0; i<12; i++){
        cout<<heroes[i]<<endl;
    }

    // Pause
    cout<<endl<<endl<<endl<<"Please Close Console Window"<<endl;
    cin.ignore('\n', 1024);
    return(0);
}

Ok I got it worked out!!!

http://ideone.com/ugLZ7

Here is the code... (how do i post code on this form btw?)

It is nearly exactly teh same but using complete string comparisons and copies.


Solution

  • You don't seem to have understood bubble-sort correctly. Firstly, you are supposed to be comparing adjacent elements only, and secondly, you need to check beyond the first character if matches for two elements. I made the necessary modifications, and the relevant part of the properly working code is:

    int n=11,k,l;
    for(int i=0;i<n-1;i++){
        for(int j=0; j<n-i-1; j++){
            l = min(strlen(heroes[j]),strlen(heroes[j+1]));
            for(k=0;k<l;++k)
                if(heroes[j+1][k]<heroes[j][k]){ swap(heroes[j],heroes[j+1]); break; }
                else if(heroes[j+1][k]>heroes[j][k]) break;
            if(k==l and strlen(heroes[j])>strlen(heroes[j+1]))
                swap(heroes[j],heroes[j+1]);
            }
        }
    

    PS : You don't need to output the array using for loops that have 12 iterations. The last iteration just produces garbage values.