Bubble Sort matrix, bi dimensional vector

Asked

Viewed 1,648 times

0

I’m having trouble creating a Bubble Sort order a square matrix. Simple vector I get, the problem eh with matrix. I tested several ways and nothing.

At the moment I am in the following configuration:

void ordem(int *matriz [][n])
{
    int temp, l, c;
    for(l=0; l<n; l++){
      for(c=0; c<=n-l; c++){
        if(matriz[l][c] > matriz[l][c+1]){
          temp = matriz[l][c];
          matriz[l][c] = matriz[l][c+1];
          matriz[l][c+1] = temp;
        }
      }
    }
}

If you need to put the whole code.

2 answers

1


Look, reading your code, his problem is this... The first for() makes the interactions passing from line to line in your matrix. The second for() makes the interactions by traversing the matrix columns. When you find a value at position c that is greater than c+1, both on the same line, you plot the position values. OK! But that’s not the Bubble Sort. You need to create a third loop to continue checking that that element that was in the c column is still larger than in c-1. For example:

7 8 5 4
0 6 5 4
1 4 2 5
2 4 2 5

Let’s run your code only on the first line:
1-7 is greater than 8? no! continues the loop...
2-8 is bigger than 5? yes! exchange! continues loop...
now we have in the first line the following:

7 5 8 4

3-8 is bigger than 4? yes! exchange! continues loop...

7 5 4 8

See the problem? He doesn’t keep ordering...

My suggestion is this: it gets "ugly" to create an extra loop there... I guess. Create a program that traverses the line of the matrix and calls the Bubble Sort for each line. Up because, each line is still an array, right? And vectors you know how to organize. Pass to the Bubble function you created for vectors the matrix line. Ready.

0

It seems to me that there is some confusion of integers and pointers. In function appears:

(apontador > apontador )    // possivel mas não me parece que queiras isso
int = apontador             // raramente é o pretendido
apontador = apontador       // neste caso não me parece que seja o que queres

Therefore I would suggest to review:

  • Matrix declaration (currently you have an array of pointers for integers) --> suitable for array of intercoms (ex int matriz[][n])
  • cc -Wall to help point out some of these situations

Moving on to serious things, ordering a square can have many possible specifications: If I understand correctly, your algorithm is ordering the lines but not the lines between them.

What was the intended result?

  • The intention is to organize the rows and not the columns

  • @Maximilianomeyer, courage: (completes the statement), corrects the statement, amends and gives us the final answer to which you have come for us to vote!

Browser other questions tagged

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