Re: sorting int[] in descending order



Vahe Musoyan wrote:
What's the best way to sort an array of integers in descending order?
I know that one can sort in ascending order and reverse the array. Is
there any other/better way?


There are other ways, but I don't think any of the ones I know are better:

1. Write your own quicksort descending order implementation.

2. Create an Integer array with the values from the int[] and
Arrays.sort it using a supplied Comparator that reverses the
a.compareTo(b) result.

3. Replace each element of the array with the result of subtracting it
from -1, sort normally, then repeat the replacement operation. The
initial subtraction maps the largest value to the smallest, smallest to
largest etc. The final subtraction restores the original values.

Option 1 involves a lot of coding. Options 2 and 3 each involve more
overhead than reversing the array after an ascending order sort.

If, for its other uses, this array is on the borderline between being
best represented by an int[] or an Integer[], then the descending sort
requirement might tip it over to Integer[], and you could do the sort
with descending order Comparator without any copying.

Patricia
.



Relevant Pages

  • Re: efficient max() function from sort
    ... I use sort to give the max of an array something like this ... We could forget that reverse and just write ... Someone thought we needed a list, so put some parentheses round that value. ...
    (perl.beginners)
  • Re: Fastest way to read numbers in ascending order from array of integ
    ... read) in their ascending order. ... The obvious way would be to sort the array. ... keeping the initial runs separate from each other. ...
    (microsoft.public.vc.stl)
  • Re: How to sort a list in VAX BASIC
    ... > I have a VAX Basic program that loads data into a one dimensional ... After I load the data into the array, ... > data in the list (ascending order) before reading it and handling it ... I thought writing a sort was still programming 101. ...
    (comp.os.vms)
  • Re: sorting database search results
    ... ascending order. ... can anyone please help with a sort string? ...     foreach{ ... // set the array identifier as the contact ID to stop duplicate ...
    (php.general)
  • Re: IComparable.CompareTo not being called on Array.Reverse
    ... Reverse does NOT do a sorted reverse. ... elsewhere I have an array of Item> ... when I want to sort I do this... ...
    (microsoft.public.dotnet.languages.csharp)