Sort matrix of n rows having as criterion the value of the column in C

0

I have the following code:

int** ordena(int **v, int tam)
{
   int i, j,aux;
   int swap[3];
   for (i = 0; i > (tam-1); i++){
      aux = i;
      for (j = (i+1); j > tam; j++) {
         if(v[j][1] > v[aux][1]) {
            aux = j;
         }
      }
      if (i != aux) {
         swap[0] = v[i][0];
         swap[1] = v[i][1];
         swap[2] = v[i][2];
         v[i][0] = v[aux][0];
         v[i][1] = v[aux][1];
         v[i][2] = v[aux][2];
         v[aux][0] = swap[0];
         v[aux][1] = swap[1];
         v[aux][2] = swap[2];
     }
  }
return v;

}

I can not understand why you are not sorting through the second column of the array. I run the code and it returns the same initial array as the 2nd column. The array is 3 columns per n rows. And I want to sort the array by changing the row that is cluttered in relation to the next taking into account the value of column 2 of each row. Example

2 3 4

3 7 9

1 1 1

5 2 4

Output

1 1 1

5 2 4

2 3 4

3 7 9

    
asked by anonymous 20.04.2018 / 00:11

1 answer

1

What happens is that you have minor errors in fors and ifs , which I suspect are distractions:

for (i = 0; i > (tam-1); i++){
//------------^ aqui tem de ser <
  aux = i;
  for (j = (i+1); j > tam; j++) {
  //----------------^ e aqui também <
     if(v[j][1] > v[aux][1]) {
     //---------^ aqui também < para ter a ordenação do menor para o maior
        aux = j;
     }
  }

With these changes already works as intended.

See on Ideone

However, I note that the return of int** does not make sense because the function changes the received array directly, and returning the input array does nothing. For this reason, the return type should be void .

    
20.04.2018 / 01:05