[SOLVED] Sorting array in descending order?

• 03-11-2009, 07:38 PM
dan0
[SOLVED] Sorting array in descending order?
What is the best way to convert an int array from ascending order to descending order?

For example, how can I convert exArray1.1 to exArray1.2?

(exArray1.1)
example[0] = 1
example[1] = 2
example[2] = 3
--------------
(exArray1.2)
example[0] = 3
example[1] = 2
example[2] = 1
• 03-11-2009, 08:06 PM
angryboy
is the array already sorted and you want to reverse it? or do you have to sort then reverse?
• 03-11-2009, 08:07 PM
emceenugget
just reverse it. it's not hard to do.
• 03-11-2009, 08:33 PM
dan0
Quote:

Originally Posted by angryboy
is the array already sorted and you want to reverse it? or do you have to sort then reverse?

The array is already sorted, and I want to reverse it. I put the following code together to sort it in descending order, but there has to be a better way, right?

Code:

```        private int[] descendSort(int[] array){                 int[] tempArray = new int[array.length];                 for (int i = array.length-1; i <= 0; --i){                         for (int j = 0; j < array.length-1; ++i){                                 tempArray[j] = array[i];                         }                 }                 return tempArray;         }```
• 03-11-2009, 08:59 PM
Fubarable
You don't want to use nested for loops here, trust me. Try to figure out what this would do on paper with an array of 3 items. No, much better is to use a single for loop, and figure out how to use "i" and the array length so that you'll get a proper index for the second array.

Code:

```  private int[] descendSort(int[] array)   {     int[] tempArray = new int[array.length];     for (int i = 0; i < tempArray.length; i++)     {       // int j = some function of i and tempArray.length;       tempArray[j] = array[i];     }     return tempArray;   }```
• 03-11-2009, 09:42 PM
dan0
Quote:

Originally Posted by Fubarable
No, much better is to use a single for loop, and figure out how to use "i" and the array length so that you'll get a proper index for the second array.

Thanks for the help. The function I used to find "j" was:
Code:

`(array.length-1)-i`
After inserting the above function, the method properly sorted in descending order.

Lastly, Arrays don't have a reverse method like Collections do, right?
• 03-11-2009, 09:45 PM
Fubarable
Very good, and you're welcome. I didn't know whether Arrays had this method or not, so I looked it up in the API.
• 03-11-2009, 09:46 PM
Fubarable
But collections can be used if the array holds objects:
Code:

```  public static void main(String[] args)   {     String[] stringArray =     { "1", "2", "3", "4", "5", "6" };     System.out.println(Arrays.toString(stringArray));     List<String> stringList = Arrays.asList(stringArray);     Collections.reverse(stringList);     String[] stringArray2 = stringList.toArray(new String[0]);     System.out.println(Arrays.toString(stringArray2));   }```
• 03-11-2009, 10:05 PM
dan0
I too went through the API and was a bit surprised that Arrays didn't have something similar to Collection's reverse method... I thought I may have missed it.

I appreciate the example of using Collection's reverse method, if the array holds objects.
• 03-11-2009, 10:14 PM
Fubarable
I too was a bit surprised. Perhaps there is some deep reason having to do with an array being allowed to hold primitives, but again, I don't know.
• 03-12-2009, 07:43 PM
glhansen
If you want a general solution to sorting things as you please, you can use the Comparable interface. You need to define a method, compareTo(), which determines whether an item should be placed before or after another item. It seems like a lot of code below to set up and demonstrate it (and I'm not saying I've done it in a particularly economical way, either), but in my own experiments I've made a class with a number of different fields, and methods that set flags for which field to sort on, and whether ascending or descending. Maybe there's something useful here for you.

import java.util.*;

public class Sorter implements Comparable<Sorter> {

private static Boolean ascending = true;
int number;

Sorter(int n) {
number = n;
}

public int compareTo(Sorter temp) {
int i;

if (this.number > temp.number)
i = 1;
else if (this.number < temp.number)
i = -1;
else i = 0;

if (ascending == false)
i = -i;
return i;
}

public void set(int n) {number = n;}
public int get() {return number;}
public static void sortAscending() {ascending = true;}
public static void sortDescending() {ascending = false;}

public static void main(String[] args) {
ArrayList<Sorter> l = new ArrayList<Sorter>();
for (int i = 0; i < 5; i++)

System.out.println("Original order:");
int i = l.size();
int j = 0;
while (j < i) {
System.out.println(l.get(j).get());
j++;
}
System.out.println("\n");

System.out.println("Descending order:");
Sorter.sortDescending();
Collections.sort(l);
j = 0;
while (j < i) {
System.out.println(l.get(j).get());
j++;
}
}
}
• 04-14-2009, 02:46 PM
vijay24805
In compareto(object 1,obect 2) and compare() method the object ar comapared and returned -ve,0 and +ve values based on the comparision --- if object1 is greater than object 2 return 0,my question in what sense the object ar compared as greater or smaller?is it the no. of characters counted and compared?

ex-obj1 let be "fun"
and obj2 let be "hello" then if we compare this two object by using overriding of
compare(obj1,obj2)
{
return obj1.compareTo(obj2);
}
how i can preddict wether it is -1,1 or zero?
• 04-15-2009, 01:47 AM
glhansen
Strings already have a compareTo function. The relevant documentation is here.

Ah, heck. I can't post links because I only have 18 posts. Do a Google search on java strings.

"a value less than 0 if the argument is a string lexicographically greater than this string"

If you want to roll your own with a class that implements Comparable, docs are here.

(Do a Google search on java comparable.)

Specifically, "Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."

I have to be honest, I can never remember if it should be positive or negative. And, of course, it reverses if you use this.compareTo(input) or input.compareTo(this). I always resort to testing it and changing the sign if I have to.

As a point of interest, by writing your own compareTo function you can make complex comparisons between multi-field objects. The only use I've done with it is sorting, and when a class implements Comparable and has a compareTo method, you automatically get sort(). I've made classes with static variables that specify which field gets sorted on first, and which second. To use, set the sort flags, then call Collections.sort(myObjectArray). The objects in the array are of a class that implements Comparable, not the array. You can stick them in any container class.
• 04-15-2009, 09:40 PM
vijay24805
COULD YOU EXPLAIN HOW THAT REVERSE THING WORKS?
HOW DOES THE this.compareTo(input) DO REVERSE SORTING?

ReSortComparator rs = new ReSortComparator(); // #3
Arrays.sort(sa,rs);
for(String s : sa)
static class ReSortComparator
implements Comparator<String>
{
public int compare(String a, String b)
{
return b.compareTo(a);
}

HERE IN THE CODE Arrays.sort(sa,rs); WHAT IS THE VALUE OF rs? WHEN I EXECUTED THIS PART OF CODE I GOT THE ARRAY SORTED IN REVERSE ORDER.WHAT VALUE WAS ASSIGNED TO rs AND HOW DID IT HELPED THE METHOD Arrays.sort(sa,rs) TO SORT THE ARRAY IN REVERSE ORDER,THIS IS MY DOUBT?
• 04-16-2009, 01:19 AM
glhansen
Java knows how to sort primitives, but it doesn't know how to sort whatever arbitrary class that you define. So when you implement Comparable you need to write a compareTo method for your class, which returns a number less than zero if "this" is less than, or comes before, the input parameter, greater than zero if it comes after, and zero if they're the same.

The class doesn't do the sorting, and the compareTo method doesn't do the sorting. Rather, the Java class, Collections, does the sorting. Put your set of objects in a container, like an ArrayList, and tell Collections to sort the container. Collections will call the compareTo method, which you have to supply for that class, to determine which objects come before other objects, and then it will shuffle the container and sort them. And it's your compareTo method that you can define any way you like, so that's how you can control the sort order. I've used static variables in the class, with methods to set them, and the compareTo checks those variable to determine which object comes first.