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;
}
}
}
They are two loops that compare the values of two in two of the array, when a value in the later position is greater than in the previous position(if (vet[i] > vet[j]
), it changes both position. And so it continues to compare up to the last two elements.
See working on 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 code above makes:
- multiplies all indices of the vector by -1;
- sort the vector upwards;
- again multiplies all indices by -1
The result is the same, as can be seen in ideone.
I prefer the second solution: it is made on a sorting algorithm
n log(n)
– Jefferson Quesado
I saw that new functionality from Java 8 @diegofm, what do you think?
– Marconi
@Marconi to be honest, I never used that lib there. Apache Commons also has a feature to sort array of primitives, but since I have never used it myself, I only put forms using native methods. If you went to an Integer array, you could use it and it would be easier to do this.
– user28595
@diegofm I was curious too much in this lib, as I’m rusty in Java and I don’t have the IDE just gave a read even. I think it would be interesting in your answer!
– Marconi
@Marconi I will try to test later, in java8 has some features that I still kind of outdated kkk
– user28595
@diegofm quiet, already left my +1!
– Marconi
We did research in college, using Bubble Sorte, Quick Sort, and others, on Windows 10 and Linux operating systems, with identical and different processors, as they were several academics, the
Bubble Sort
was the slowest, and put slow in it.– Taffarel Xavier