88754

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

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.