Bubble sort in array, bi dimensional vector

0

I am not able to create a bubble sort that sorts a square array. Simple vector I get, the problem is with matrix. I tested it in many ways and nothing.

Currently I'm 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.

    
asked by anonymous 07.04.2015 / 06:52

2 answers

1

Look, reading your code, his problem is this ... The first for () makes the interactions going from the inline row of your array. The second for () makes the interactions traversing the columns of the array. 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 bubble sort. You need to create a third loop to continue checking if that element that was in column c is still larger than the one 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? not! continues the tie ...
2-8 is greater than 5? yea! exchange! continues the tie ...
now we have in the first line the following:

7 5 8 4

Is 3-8 greater than 4? yea! exchange! continue the loop ...

7 5 4 8

See the problem? He does not continue to order ...

My suggestion is as follows: it's "ugly" to create a bond over there ... I think. Create a program that traverses row by row of array and calls bubble sort for each row. Why, each line is still a vector, right? And vectors you know how to organize. Pass to the bubble function that you created to array array vectors. Ready.

    
14.04.2015 / 20:30
0

It seems to me that there is some confusion of integers and pointers. In the function it 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

Porting suggested review:

  • the declaration of the matrix (you now have an array of pointers for integers) - >
  • int matriz[][n] to help pinpoint some of these situations

Turning to serious things, Sorting a square can have many possible specifications: If I understand correctly, your algorithm is sorting the lines but not the lines.

What is the intended result?

    
07.04.2015 / 09:25