Sort Specific Column of 2D array

Greetings plusplussers. I'm strugging with creating a user defined function. It has three purposes. 1: Receive user input to select a column from a 3x5 array (already created in the main function) to sort. 2: Sort that column in ascending order. 3: Print out the full 3x5 displaying the selected column sorted and the others untouched. This is for a class and I'm struggling with getting the desired output. I'd really appreciate any general hints or tips I could use to understand why my code isn't doing what I want from it. Cheers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 void sort2D (int arr[3][5], const int rows, const int columns)
{
    int usercol;
    cout << "Please enter the number of the column you want to sort."<<endl;
    cin >> usercol;


    int mincol=arr[0][usercol-1];

    for (int row_index=1; row_index<rows; row_index++)
        {
            int nextrow=(row_index+1);
            int column_index = (usercol-1);

                if (mincol<arr[row_index][column_index])
                    {
                        swap(mincol, arr[row_index][column_index]);
                    }

    }
cout << arr;
}
Currently you sort only the first row. Since mincol is a copy you only swap the copy. The first row is unaffected. So change mincol to a reference:

int &mincol=arr[0][usercol-1]; // Notice the &

To sort all rows you need an outer loop which is similar to the loop on line 10, but it starts with 0. For mincol it would look something like this:

int &mincol=arr[outer_row_index][usercol-1]; // Notice the &

By the way: The name of this sorting algorithm is bubble sort.
Topic archived. No new replies allowed.