Generic Sort

	/**
	 * class using quick sort
	 */
	class Sorter {
		
		public <T extends SortElement<T>> void sort(ArrayList<T> array) {
			if (array.size() < 2) 
				return;
			quicksort(array,0,array.size()-1);
		}
		
		private <T extends SortElement<T>> void quicksort(ArrayList<T> array, int left, int right) {
			if (left < right) {
				int pivotIndex = (left + right)/2;
				int pivotNewIndex = partition(array,left,right,pivotIndex);
				quicksort(array,left,pivotNewIndex-1);
				quicksort(array,pivotNewIndex+1,right);
			}
		}
		
		private <T extends SortElement<T>> int partition(ArrayList<T> array, int left, int right, int pivotIndex) {
			T pivotValue = array.get(pivotIndex);
			T tempValue;
			tempValue = array.get(pivotIndex);
			array.set(pivotIndex, array.get(right));
			array.set(right, tempValue);
			int storeIndex = left;
			for (int i=left;i<right;i++) {
				if (array.get(i).compare(pivotValue) == -1) {
					tempValue = array.get(storeIndex);
					array.set(storeIndex, array.get(i));
					array.set(i, tempValue);
					storeIndex++;
				}
			}
			tempValue = array.get(right);
			array.set(right, array.get(storeIndex));
			array.set(storeIndex, tempValue);
			return storeIndex;
		}
		
	}
	
	abstract class SortElement<T> {
		abstract public int compare(T element2);
	}
	
	/**
	 * class for sorting subject tags
	 */
	class TagSortElement extends SortElement<TagSortElement>{
		String name;
		int index;
		
		public int compare(TagSortElement element2) {
			if (this.index == element2.index) {
				return 0;
			} else if (this.index > element2.index) {
				return 1;
			} else {
				return -1;
			}
		}
	}
	
	/**
	 * class for sorting subject
	 */
	class SubjectSortElement extends SortElement<SubjectSortElement>{
		String groupTitle;
		long visits;
		
		public int compare(SubjectSortElement element2) {
			if (this.visits == element2.visits) {
				return 0;
			} else if (this.visits > element2.visits) {
				return 1;
			} else {
				return -1;
			}
		}
	}

你可能感兴趣的:(Generic Sort)