Java Reference
In-Depth Information
Example 2•9: Sorter.java (continued)
public static void sort(Object[] a, Object[] b,
int from, int to,
boolean up, Comparer c)
{
// If there is nothing to sort, return
if ((a == null) || (a.length < 2)) return;
// This is the basic quicksort algorithm, stripped of frills that can
// make it faster but even more confusing than it already is. You
// should understand what the code does, but don't have to understand
// just why it is guaranteed to sort the array...
// Note the use of the compare() method of the Comparer object.
int i = from, j = to;
Object center = a[(from + to) / 2];
do {
if (up) { // an ascending sort
while((i < to) && (c.compare(center, a[i]) > 0)) i++;
while((j > from) && (c.compare(center, a[j]) < 0)) j--;
} else { // a descending sort
while((i < to) && (c.compare(center, a[i]) < 0)) i++;
while((j > from) && (c.compare(center, a[j]) > 0)) j--;
}
if (i < j) {
Object tmp = a[i]; a[i] = a[j]; a[j] = tmp; // swap elements
if (b != null) { tmp = b[i]; b[i] = b[j]; b[j] = tmp; } // swap
}
if (i <= j) { i++; j--; }
} while(i <= j);
if (from < j) sort(a, b, from, j, up, c); // recursively sort the rest
if (i < to) sort(a, b, i, to, up, c);
}
/**
* This nested class defines a test program that demonstrates several
* ways to use the Sorter class to sort ComplexNumber objects
**/
public static class Test {
/**
* This subclass of ComplexNumber implements the Comparable interface
* and defines a compareTo() method for comparing complex numbers.
* It compares numbers based on their magnitude. I.e. on their distance
* from the origin.
**/
static class SortableComplexNumber extends ComplexNumber
implements Sorter.Comparable {
public SortableComplexNumber(double x, double y) { super(x, y); }
public int compareTo(Object other) {
return sign(this.magnitude()-((ComplexNumber)other).magnitude());
}
}
/** A a test program that sorts complex numbers in various ways. */
public static void main(String[] args) {
// Define an array of SortableComplexNumber objects. Initialize it
// to contain random complex numbers.
SortableComplexNumber[] a = new SortableComplexNumber[5];
for(int i = 0; i < a.length; i++)
a[i] = new SortableComplexNumber(Math.random()*10,
Search WWH ::




Custom Search