Java Sorting Arrays
The Java API includes a prefabricated method for sorting arrays. According to the official documentation, this method is a tuned quicksort, so we don’t need to write one.One example:
Long longArray[] = new Long[10];
for(int i=0; i<longArray.length; i++){
//just a random number between 0 - 9
longArray[i] = new Long((new Double(Math.random()*i)).longValue());
}Arrays.sort(longArray);
for(int i=0; i<longArray.length; i++){
System.out.print(longArray[i].longValue()+”-”);
–> This will output a list of numbers sorted in an Ascending way, (like 0,1,2,3,4…).
If we want to sort it in a reverse order (Descending), we should use: Arrays.sort(longArray,java.util.Collections.reverseOrder());
That simple.
But it isn’t the most interesting part.
We can sort objects according to some of its attributes.
To sort objects, those objects must implements the Comparable interface. For example:
//Declaring the object
class IndexedFreq implements Comparable{
public int idx;
public int freq;public IndexedFreq(int idx, int freq){
this idx = idx;
this.freq = freq;
}public int compareTo(Object obj){
IndexedFreq idxfreq2 = (IndexedFreq )obj; //We receive the object to compare
int f1 = freq; //and we can access to the second object which is compared
int f2 = idxfreq2.freq//Here we decide which object must come first
if(f1<f2){
return -1;
}else if(f2>f1){
return 1;
}
return 0; //the freqs are equal
}
}//Using the object
public class UseIndexedFreq{
public static void main(String args[]){
IndexedFreq idxFreqArray[] = new IndexedFreq[10];
for(int i=0; i<idxFreqArray.length; i++){
idxFreqArray.idx = i;
idxFreqArray.freq = (new Double(Math.random()*i)).intValue();
}Arrays.sort(idxFreqArray,java.util.Collections.reverseOrder());
}
In the last example I’ve created an array of IndexedFreq objects, initializing them with an index (idx) and a random frequency (freq)
As shown above, the Arrays.sort(idxFreqArray,java.util.Collections.reverseOrder()); method will sort the array, in this case according to the freq value, in a Descending order.
Note that we can do the public int compareTo(Object obj) method as complex as we like. For example we could use a new attribute in the object to define if this object must have a freq=0 so it will be allocated at the begining/end of the array (depending of the order of the sort).



on September 28th, 2006 at 12:27 pm
Thks man!
this “java.util.Collections.reverseOrder()” works great!