|
Descending Arrays
There are a number of operations in programming that we don't need very often, but when we do need them, we really need them. If the operation is a Big Deal, it is fertile ground for ISVs, like conceptGO. For smaller areas, "should be free" fits the bill. One of these areas is sorting arrays in descending order. The java.util.Arrays class does a good job of sorting, but has no obvious means for any order other than ascending. In this article, we'll take a look at some different ways to accomplish sorting arrays in descending order.
One fairly obvious way is to sort the array in ascending order, then read it backwards. This method will work for any array. The downside is that a lot of extra, duplicated work is often required. reverseRead() in the accompanying code provides an example of reading an array backwards. The problem is that it is almost impossible to have one method or class handle everything we need to do and then read the array in reverse.
For numeric arrays, there is a fairly simple option: reverse the sign on each element, sort ascending, then re-reverse the sign to get the original values. This works works very well for arrays of primitive numerics and has almost no drawbacks, other than a slight speed degradation. It is tedious to write a method for each numeric type, but this is a one-time task. This type of descending sort is illustrated in the reverseInt() method.
The last method we will look at in this article uses a swap algorithm to put the values in descending order. The basics are: sort the array in ascending order, then swap the highest and lowest; adjust the indexs and swap the next highest and lowest; continue until the indexes cross. This method will work for any type of array, again with a slight speed degradation. swapDescend() illustrates the swap method.
In all of these methods, you'll notice that I've taken a shortcut, mostly to make the code smaller: None of the methods take an input argument. They just use the already created arrays in the class. Obviously, general purpose methods would take the original unsorted array as input. The pedal to the metal group will also notice that none of these methods involve any great new sorting algorithms. The efficiency choice here was to leverage existing code, so these methods won't suit everyone. That's it for now; Happy sorting!
|