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

Asked

Viewed 671 times

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 don’t understand why you’re not sorting through the second column of the matrix. I run the code and return the same disordered initial matrix for the 2 column. The matrix is 3 columns per n rows. And I want to sort the matrix by changing the row that is disordered relative to the next one taking into account the value of column 2 of each row. Example

2 3 4

3 7 9

1 1 1

5 2 4

Exit

1 1 1

5 2 4

2 3 4

3 7 9

1 answer

1


What’s going on is that there are little mistakes in fors and ifs, that 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 you want.

Check it out at Ideone

I note however that the return of int** which has no sense because the function changes the received array directly, and return the input array at nothing. For this reason the type of return should be void.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.