reverseOrder () In java not reversing

1

I have a method in java to sort a vector in descending method, but when I run the test it returns the unordered vector.

Follow 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 .random() function in the test file

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

When I test the function:

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

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

It is sorting right 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());
}
    
asked by anonymous 20.06.2018 / 00:05

1 answer

2

You can do this:

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 (including doing this is deprecated since Java 9). With direct assignment, the compiler does the autoboxing alone.

    
20.06.2018 / 01:12