How to sort vector in descending order?

4

How do I place a vector in descending order?

    public static void vetor() {
      int[] vet = {
          7,
          4,
          10,
          8,
          2,
          5
      };
      Arrays.sort(vet);
      //Comando para colocar em ordem decrescente.
      for (int i = 0; i < vet.length; i++) {
          System.out.println(vet[i] + "");
      }

  }
    
asked by anonymous 22.06.2017 / 00:15

3 answers

5

To sort an array in descending order, you can use the sort algorithm bubble sort :

for (int i = 1; i < vet.length; i++) {
    for (int j = 0; j < i; j++) {
        if (vet[i] > vet[j]) {
            int temp = vet[i];
            vet[i] = vet[j];
            vet[j] = temp;
        }
    }
}

There are two loops that compare the two-in-two values of the array, when a value in the posterior position is greater than the value in the previous position (% cos_de%), it changes both positions. And so it goes on comparing even the last two elements.

See working at IDEONE

Another interesting solution I found in SOEn is this:

for(int i=0;i<vet.length;i++) {

    vet[i]=-vet[i];
}

Arrays.sort(vet);

for(int i=0;i<vet.length;i++) {

    vet[i]=-vet[i]; 
}

The above code does:

  • multiplies all vector indices by -1;
  • sort the vector in ascending order;
  • re-multiplies all indices by -1

The result is the same, as can be seen in the ideone .

    
22.06.2017 / 01:28
0

How about doing this?

Arrays.sort(vet);
int[] vetAux;

int contador = 0;
for(int i=vet.length - 1;i >= 0;i--) {
    vetAux[contador]=vet[i]; 
    contador++;
}
    
22.06.2017 / 20:43
-3
//Ordem Decrescente

import java.util.Scanner;
public class OrdemDecrescente {

    public static void main(String[] args) {

     int cont = 1;
     int[] vet = new int[5];

     Scanner sc = new Scanner(System.in);
    for (int i = 0; i < vet.length; i++){  
        System.out.print("Digite "+cont+"° número: \t");
        vet[i] = sc.nextInt();
        cont++;
        }

    for (int i = 1; i < vet.length; i++) {
        for (int j = 0; j < i; j++) {
            if (vet[i] > vet[j]) {
                int aux = vet[i];
                vet[i] = vet[j];
                vet[j] = aux;
            }
        }
    }
    System.out.println("Array em ordem decrescente:");
    for (int n : vet) {
        System.out.print(n + " ");
        }
    }
}
    
10.09.2018 / 01:19