my dog learned polymorphism*
The moose likes Beginning Java and the fly likes sorting arrays in descending order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "sorting arrays in descending order" Watch "sorting arrays in descending order" New topic
Author

sorting arrays in descending order

Kevin Knight
Greenhorn

Joined: Jun 27, 2008
Posts: 2
Real quick questions... How do I sort an array of int in descending order. Thanks for any help you can give.
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Originally posted by Kevin Knight:
Real quick questions... How do I sort an array of int in descending order. Thanks for any help you can give.


Quick (and hopefully correct) answer: Transfer over to an Integer array, then use Arrays.sort using an appropriate Comparator<Integer> object.

For instance:

[ June 28, 2008: Message edited by: pete stein ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
Welcome to JavaRanch

Pete has already given you the "correct" answer; now I shall give you the answer you want for homework.

Write a class called ArrayUtil or similar and in it implement a public static void swapPair(int[] array, int index1, int index2) method. Pass an array and the numbers of the two elements you want to swap to it. That will swap the two elements. Remember you need a temporary element in the method which will hold the original value while you swap.

Implement a public static void sort(int[] array) method which takes one of the better-known sorting algorithms. Several links to sorting algorithms available: see which of these is most useful: 1 2 3. Lots more available on Google.

Probably best to implement a public static void reverse(int[] array) method which uses the swap method you have already written to reverse the array; that is better than swapping < for > in the sort method.

Use the sort method then the reverse method. And lots of nice marks for you!
Kevin Knight
Greenhorn

Joined: Jun 27, 2008
Posts: 2
thanks guys
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
Originally posted by Kevin Knight:
thanks guys
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: sorting arrays in descending order
 
Similar Threads
dESCENDING ORDER
how to sort name -value pair in descending order
Help
Sorting by 3 variables dynamically in arrayList
Recent Transaction Records