1 package net.sourceforge.phpdt.internal.ui.util;
3 import java.util.Comparator;
5 import org.eclipse.jface.util.Assert;
8 * Quick sort to sort key-value pairs. The keys and arrays are specified
11 public class TwoArrayQuickSorter {
13 private Comparator fComparator;
18 public static final class StringComparator implements Comparator {
19 private boolean fIgnoreCase;
21 StringComparator(boolean ignoreCase) {
22 fIgnoreCase= ignoreCase;
25 public int compare(Object left, Object right) {
27 ? ((String) left).compareToIgnoreCase((String) right)
28 : ((String) left).compareTo((String) right);
33 * Creates a sorter with default string comparator.
34 * The keys are assumed to be strings.
35 * @param ignoreCase specifies whether sorting is case sensitive or not.
37 public TwoArrayQuickSorter(boolean ignoreCase) {
38 fComparator= new StringComparator(ignoreCase);
42 * Creates a sorter with a comparator.
43 * @param comparator the comparator to order the elements. The comparator must not be <code>null</code>.
45 public TwoArrayQuickSorter(Comparator comparator) {
46 fComparator= comparator;
50 * Sorts keys and values in parallel.
51 * @param keys the keys to use for sorting.
52 * @param values the values associated with the keys.
54 public void sort(Object[] keys, Object[] values) {
55 if ((keys == null) || (values == null)) {
56 Assert.isTrue(false, "Either keys or values in null"); //$NON-NLS-1$
63 internalSort(keys, values, 0, keys.length - 1);
66 private void internalSort(Object[] keys, Object[] values, int left, int right) {
67 int original_left= left;
68 int original_right= right;
70 Object mid= keys[(left + right) / 2];
72 while (fComparator.compare(keys[left], mid) < 0)
75 while (fComparator.compare(mid, keys[right]) < 0)
79 swap(keys, left, right);
80 swap(values, left, right);
84 } while (left <= right);
86 if (original_left < right)
87 internalSort(keys , values, original_left, right);
89 if (left < original_right)
90 internalSort(keys, values, left, original_right);
94 * Swaps x[a] with x[b].
96 private static final void swap(Object x[], int a, int b) {