Search code examples
c++arrayssortingselection-sort

Can't pass array to a sorting function(need to sort columns, not rows)


I need to use selection sort to sort a two-dimensional array. The problem is that I need to sort array's columns, not rows. Here is how I allocate a two-dimensional array(to show the structure):

int** array = new int*[rows];
    for (int i = 0; i < rows; i++) {
        array[i] = new int[columns];
    }

Then I add some items into it. Here is my sorting function:

void selectionSort(int* arr, int n)
{
    int i, j, min_idx;

    for (i = 0; i < n; i++)
    {
        min_idx = i;
        for (j = i + 1; j < n; j++)
            if (arr[j] < arr[min_idx])
                min_idx = j;

        swap(&arr[min_idx], &arr[i]);
    }
}

I'm not specifying swap since it is self-explanatory.

So, again, I need to sort every column of a matrix. For example:

Input:

5 3 1

2 0 9

4 2 6

Output:

2 0 1

4 2 6

5 3 9

Any ideas on how to do that? Right now I transpose the matrix twice and in-between transpositions I sort it, but I don't think it is a good option because of its slowness.


Solution

  • You might template your function to have a getter of int:

    template <typename F>
    void selectionSort(F f, int size)
    {
        for (int i = 0; i < size; i++)
        {
            int min_idx = i;
            for (int j = i + 1; j < size; j++)
                if (f(j) < f(min_idx))
                    min_idx = j;
    
            swap(f(min_idx), f(i));
        }
    }
    

    So, in one dimension, you have your old:

    selectionSort([arr](int i) -> int&{ return arr[i]; }, n);
    

    and for column:

    selectionSort([arr, j](int i) -> int&{ return arr[i][j]; }, n);