1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.core.util;
14 * The SortOperation takes a collection of objects and returns
15 * a sorted collection of these objects. The sorting of these
16 * objects is based on their toString(). They are sorted in
19 public class ToStringSorter {
20 Object[] sortedObjects;
21 String[] sortedStrings;
23 * Returns true if stringTwo is 'greater than' stringOne
24 * This is the 'ordering' method of the sort operation.
26 public boolean compare(String stringOne, String stringTwo) {
27 return stringOne.compareTo(stringTwo) < 0;
30 * Sort the objects in sorted collection and return that collection.
32 private void quickSort(int left, int right) {
33 int originalLeft = left;
34 int originalRight = right;
35 int midIndex = (left + right) / 2;
36 String midToString = this.sortedStrings[midIndex];
39 while (compare(this.sortedStrings[left], midToString))
41 while (compare(midToString, this.sortedStrings[right]))
44 Object tmp = this.sortedObjects[left];
45 this.sortedObjects[left] = this.sortedObjects[right];
46 this.sortedObjects[right] = tmp;
47 String tmpToString = this.sortedStrings[left];
48 this.sortedStrings[left] = this.sortedStrings[right];
49 this.sortedStrings[right] = tmpToString;
53 } while (left <= right);
55 if (originalLeft < right)
56 quickSort(originalLeft, right);
57 if (left < originalRight)
58 quickSort(left, originalRight);
61 * Return a new sorted collection from this unsorted collection.
62 * Sort using quick sort.
64 public void sort(Object[] unSortedObjects, String[] unsortedStrings) {
65 int size = unSortedObjects.length;
66 this.sortedObjects = new Object[size];
67 this.sortedStrings = new String[size];
69 //copy the array so can return a new sorted collection
70 System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size);
71 System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size);
73 quickSort(0, size - 1);