/*
 *	EasyScout Boy Scouts of America tracking software.
 *	http://www.easyscout.org/
 *
 *	Copyright (C) 2000 Conan C. Albrecht
 *	conan@warp.cx
 *
 *	This program is released under the GNU license so tech-savvy
 *	Boy Scouts and others can enhance the program for the use
 *	of all.  Please e-mail changes to my address above so I can
 *	reintegrate into the main program at http://www.easyscout.org/.
 *	This way, all users mutually benefit one another in the spirit of
 *	scouting.
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License
 *	as published by the Free Software Foundation; either version 2
 *	of the License, or (at your option) any later version.
 *
 * 	Any and all changes to the program code must be documented with
 *  date, author name and e-mail, and a short description.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package cx.warp.scout;

import java.util.*;

/** Implements sorting algorithms for Vectors */
public class Sort extends java.lang.Object{

	/** Sorts a vector of Sortable or String objects (all of one or
			the other) using the quicksort algorithm */
	public static void quicksort(Vector vec, Comparator c) {
		// short circuit
		if ((vec == null) || (vec.size() <= 1))
			return;

		doQuickSort(vec, 0, vec.size() - 1, c);
	}//quicksort

	/** Helper algorithm for the quicksort method */
	static void doQuickSort(Vector vec, int l, int r, Comparator c) {
		int i, j;
		Object s;
		if (r > l) { // only sort if we haven't crossed
			s = vec.elementAt(r);
			i = l - 1; // i is lower bound
			j = r;     // j is upper bound
			while (true) {
				while ((i < r) && c.compare(vec.elementAt(++i), s) < 0);
				while ((j > l) && c.compare(vec.elementAt(--j), s) > 0);
				if (i >= j)
					break;
				swap(vec, i, j);
			}//while
			swap(vec, r, i);

			doQuickSort(vec, l, i - 1, c);
			doQuickSort(vec, i + 1, r, c);
		}//if
	}//doQuickSort

	/** Swaps two objects in a vector */
	static void swap(Vector vec, int index1, int index2) {
		Object s1 = vec.elementAt(index1);
		vec.setElementAt(vec.elementAt(index2), index1);
		vec.setElementAt(s1, index2);
	}//swap

}
