`

快速排序 Quicksort

阅读更多

 

package com.tnt.sortingalgorithm;

import java.util.Comparator;
import java.util.Random;

/**
 * 快速排序
 * 
 * @author Frankco
 * 
 */
public class Quicksort {
	public static final Random RND = new Random();

	/**
	 * swap译为:交换
	 * @param array
	 * @param i
	 * @param j
	 */
	private static void swap(Object[] array, int i, int j) {
		Object tmp = array[i];
		array[i] = array[j];
		array[j] = tmp;
	}

	/**
	 * Comparable和Comparator的区别?
	 * Comparable适合用于将实体对象排序
	 * @param <E>
	 * @param array
	 * @param begin
	 * @param end
	 * @param cmp
	 * @return
	 */
	private static <E> int partition(E[] array, int begin, int end,
			Comparator<? super E> cmp) {
		int index = begin + RND.nextInt(end - begin + 1);
		E pivot = array[index];
		swap(array, index, end);
		for (int i = index = begin; i < end; ++i) {
			if (cmp.compare(array[i], pivot) <= 0) {
				swap(array, index++, i);
			}
		}
		swap(array, index, end);
		return (index);
	}

	/**
	 * 递归
	 * @param <E>
	 * @param array
	 * @param begin
	 * @param end
	 * @param cmp
	 */
	private static <E> void qsort(E[] array, int begin, int end,
			Comparator<? super E> cmp) {
		if (end > begin) {
			int index = partition(array, begin, end, cmp);
			qsort(array, begin, index - 1, cmp);
			qsort(array, index + 1, end, cmp);
		}
	}

	public static <E> void sort(E[] array, Comparator<? super E> cmp) {
		qsort(array, 0, array.length - 1, cmp);
	}

	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		Integer[] arr = { 11, 52, 6, 8, 3, 4, 5, 7, 4, 6, 69, 8, 2, 5, 5, 2, 4,
				2 };
		sort(arr, new Comparator<Integer>() {
			public int compare(Integer a, Integer b) {
				if (a > b)
					return 1;
				else if (a < b)
					return -1;
				else
					return 0;
			}
		});
		
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}
分享到:
评论
Global site tag (gtag.js) - Google Analytics