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 .