Home Java Java-tips Data Arrays Sorting Arrays

Ask Questions?

View Latest Questions


 
 

Sorting Arrays
Posted on: July 26, 2006 at 12:00 AM
Why you shouldn't write your own sort

Java Notes

Sorting Arrays

Why you shouldn't write your own sort

A favorite computer science topic it sorting, putting a collection of data in some order. Typically this is done for arrays. Textbooks cover both the slow, O(n2), sorts (eg, selection, insertion, and bubble sorts) and fast, O(n log n), sorts (quick sort, heap sort, etc). These are interesting problems, give students a lot of practice with arrays, bring up important tradeoffs, and are generally quite educational.

However, the Java library already has sort methods that are more efficient, more general, and more correct than anything you are likely to write yourself. And they are already written. Professional programmers use one of the java.util.Arrays.sort() methods; they do not write their own, except perhaps in unusual cases.

Other data structures. There are sort methods in the java.util.Collections class which can be used to sort other kinds of data structures (eg, ArrayList), and there are data structures such as TreeMap that keep elements sorted based on a key.

Sorting Arrays with Arrays.sort(...)

The java.util.Arrays class contains a number of static methods for sorting arrays, both arrays of primitive types and Object types. The sort method can be applied to entire arrays, or only a particular range.

MethodDescription
Arrays sort methods
Arrays.sort(pa);Sorts the elements of the array of a primitive type into ascending order using their natural ordering.
Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.
Arrays.sort(oa);Sorts the elements of the array of an obj