An Efficient Sorting Framework

The sorting methods provided by the JDK are perfectly adequate for most situations, and when they fall short, the techniques illustrated in the previous section often speed things up as much as is required. However, if you work on a project where varied and flexible sorting capabilities are needed, sorting is one area of performance tuning where it is sensible to create a framework early during the development cycle. A good sorting framework should allow you to change sorting-algorithm and comparison-ordering methods in a generic way, without having to change too much in the application.

Providing support for arbitrary sorting algorithms is straightforward: just use sorting interfaces. There needs to be a sorting interface for each type of object that can be sorted. Arrays and collection objects should be supported by any sorting framework, along with any other objects that are specific to your application. Here are two interfaces that define sorting objects for arrays and collections:

import java.util.Comparator; import java.util.Collection; public interface ArraySorter { public void sort(Comparator comparator, Object[] arr); public void sort(Comparator comparator, Object[] arr, int startIndex, int length); public void sortInto(Comparator comparator, Object[] source, int sourceStartIndex, int length, Object[] target, int targetStartIndex); } public interface CollectionSorter { public Object[] sort(Comparator comparator, Collection c); public void sortInto(Comparator ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.