84126 # 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] > names [j]) //names = col 1 , rank = col 0 { hold1 = names [i]; hold2 = names [i]; names [i] = names [j]; names [i] = names [j]; names [j] = hold1; names [j] = hold2; } } } } ```

Thanks in advance.

### Answer1:

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.

### Answer2:

You got the bubble sort wrong. try this :

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