using System;
using System.Collections.Generic;

namespace WorldOfPeacecraft
{
	public class Quicksort<T>
	{
		public static void sort (IList<T> list, Func<T, T, bool> isSmaller)
		{
			if (list.Count != 0) {
				sort (list, 0, list.Count - 1, isSmaller);
			}
		}

		private static void sort (IList<T> list, int startIndex, int endIndex, Func<T, T, bool> isSmaller)
		{
			T tmp;
			if (endIndex - startIndex <= 0){
				return;
			}
			int pivot = endIndex;
			int rechts = endIndex - 1;
			int links = startIndex;
			while (links < rechts) {
				// while (list[links] < list[pivot] && links < rechts
				while (isSmaller(list[links], list[pivot]) && links < rechts) {
					links++;
				}
				// while (list[rechts] > list[pivot] && links < rechts
				while (isSmaller(list[pivot], list[rechts]) && rechts > links) {
					rechts--;
				}
				if (/*isSmaller (list [rechts], list [links]) && */links < rechts) {
					tmp = list [links];
					list [links] = list [rechts];
					list [rechts] = tmp;
					//links++;
				}
			}
			if (isSmaller (list [links], list [pivot])) {
				links++;
			}
			tmp = list[links];
			list[links] = list[pivot];
			list[pivot] = tmp;
			pivot = links;
			sort (list, startIndex, pivot - 1, isSmaller);
			sort (list, pivot + 1, endIndex, isSmaller);
		}
	}
}