How to use one function for both rows and columns in 2D array?

Let's say I have a sort function for 1D array

void sort(int a[], int n){
    int temp;
    for (int i = 0; i < n; i++){
       for (int j = i + 1; j < n; j++){
           if (a[i] > a[j]){
               temp = a[j];
               a[j] = a[i];
               a[i] = temp;
           }
       }
   }
}

I know how to make it sort all rows of 2D array:

for (i = 0; i < n; i++)
       sort(b[i], m); // b is 2d array n - rows m - columns

But I'm wondering what do I have to change, to be able to use the same function to sort columns instead?

2 answers

  • answered 2018-05-16 04:36 Subash

    You can transpose the incoming 2D array to exchange rows and columns and do the normal sorting.

    maybe add a flag to determine if you need to do transpose or not

  • answered 2018-05-16 04:48 Raheeb Hassan

    You can modify the sort function to traverse through columns by passing an extra argument:

    void sort(int a[][], int n, int col_index){
        int temp;
        for (int i = 0; i < n; i++){
           for (int j = i + 1; j < n; j++){
               if (a[i][col_index] > a[j][col_index]){
                   temp = a[j][col_index];
                   a[j][col_index] = a[i][col_index];
                   a[i][col_index] = temp;
               }
           }
       }
    }
    

    And then implement as follows

    for(int i=0;i<m;i++){
        sort(b,n,i);
    }
    

    Hope this helps.