Bea
Bea

Reputation: 21

Sorting a 2D array using the second column C++

I have to sort a 2D array of ranks and names (used as strings) based on the second column. I'm trying to sort it in alphabetical order but I can't seem to get it right. I'm still new to multi-dimensional arrays, so I'm still quite confused. I'm using Bubble Sort, and it is sorting the names, but not in the right order.

this is the array I'm trying to sort:

const int ROWS=6;
const int COLS=2;

string names [ROWS][COLS] = { "1", "Jacob",
                              "2", "Michael",
                              "3", "Joshua",
                              "4", "Matthew",
                              "5", "Ethan",
                              "6", "Andrew"};

this is what I get:

2 Michael
4 Matthew
3 Joshua
1 Jacob
6 Andrew
5 Ethan

and this is the sort function I'm using:

void sort (string names [][COLS], int size)
{    
    int i,j; // i = rows 
    string hold1, hold2;

    for (i=0; i < size-1; i++)
    {
        for (j=0; j < size; j++)
        {
            if (names [i][1] > names [j][1]) //names  = col 1 , rank = col 0
            {
                hold1 = names [i][1];
                hold2 = names [i][0];
                names [i][1] = names [j][1];
                names [i][0] = names [j][0];
                names [j][1] = hold1;
                names [j][0] = hold2;
            }
        }
    }
}

Thanks in advance.

Upvotes: 2

Views: 1275

Answers (2)

ShahiM
ShahiM

Reputation: 3268

You got the bubble sort wrong. try this :

for (i=0; i<size; i++)
{
    for (j=0; j < size-1; j++)
    {
        if (names [j][1] > names [j+1][1])
        {
            hold1 = names [j][1];
            hold2 = names [j][0];
            names [j][1] = names [j+1][1];
            names [j][0] = names [j+1][0];
            names [j+1][1] = hold1;
            names [j+1][0] = hold2;
        }
    }
}

Upvotes: 0

Barry
Barry

Reputation: 303087

You're actually swapping the elements back and forth. You need to make sure that when you're Bubble Sorting you're only comparing an element with a later element. That is:

for (i=0; i < size-1; i++)
{
    for (j=i+1; j < size; j++)
          ^^^^
    {
        // same as before
    }
}

Note that we can take advantage of standard utilities to make this code a lot easier to understand. The line I wrote as //same as before... what you're doing there is just swapping names[i] and names[j], which we can spell:

std::swap(names[i], names[j]);

That's just easier to understand and less error-prone.

Upvotes: 2

Related Questions