reverseOrder() In java not reversing

Asked

Viewed 124 times

1

I have a method in java to sort a vector in a decreasing method, but when I run the test it returns me the unpaired vector.

Follows the Method:

public void sort() {
  int vet[] = this.vetor;
  inverter(vet);
}

private void inverter(int[] vet) {

  Integer[] vet_x = new Integer[vet.length];
  for (int i=0; i < vet.length; i++){
      vet_x[i] = new Integer(vet[i]);
  }
  Arrays.sort(vet_x, Collections.reverseOrder());
}

The this.vetor is being generated by the function .random() in the test file

 int[] vetor = geraVetor.random(100);

When I test function:

@Override
public void sort() {
  int vet[] = this.vetor;
  inverter(vet);
}

private void inverter(int[] vet) {
 Arrays.sort(vet);
}

He’s ordering straight up in ascending order.

The function that prints the vector is this:

 public void Ordenacao() {
    GeraVetor geraVetor = new GeraVetor();

    // Crio um novo vetor
    int[] vetor = geraVetor.random(100);

    // Faço uma cópia dele
    int[] experado = Arrays.copyOf(vetor, vetor.length);

    // Ordeno a cópia com uma ordenação do Java
    //Arrays.sort(experado);

    // Teste de Ordenação
    Ordena ordena = new Ordena(vetor);
    ordena.sort();

    System.out.println("Ordenado: " + ordena.toString());
    System.out.println("Experado: " + Arrays.toString(experado));

    Assert.assertArrayEquals(experado, ordena.get());
}
  • 2

    This vector vet_x exists only in function inverter. How are you trying to use the result ?

  • I’ll edit and put the function you’re showing, it’s generating the vector, it’s retouching the vector.

  • @Isac Put that as an answer. I don’t think Patrick understood the problem there.

  • yes, I understood, it needs a return, but why use Arrays.Sort(vet); in the same way it gives me the ordered vector?

  • I understand, what would be the return or what would be called?

1 answer

2


You can do it:

private void inverter(int[] vet) {
    Integer[] vet_x = new Integer[vet.length]; // Copia criada, ...
    for (int i = 0; i < vet.length; i++) {
        vet_x[i] = vet[i]; // ... preenchida, ...
    }
    Arrays.sort(vet_x, Collections.reverseOrder()); // ... e ordenada.
    for (int i = 0; i < vet.length; i++) {
        vet[i] = vet_x[i]; // Copiando de volta para o original.
    }
}

That is, after ordering vet_x, copy the values back to vet.

Note that you do not need to use new Integer (even, to do this is deprecated since Java 9). With direct attribution, the compiler does the autoboxing alone.

  • "even, do this is deprecated since Java 9" In college we still use the AWT kkk, unfortunately only use java la, I am focused on web, wordpress + front. I think it will have to be around the solution, Thank you man

Browser other questions tagged

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