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

淺唱寂寞╮ 提交于 2019-12-11 02:31:23

问题


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.


回答1:


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.




回答2:


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;
        }
    }
}


来源:https://stackoverflow.com/questions/29712274/sorting-a-2d-array-using-the-second-column-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!