快排java实现




package sort;

public class QuickSort {
	public static final int cutoff = 3;

	/**
	 * insertion sort
	 * 
	 * @param A
	 * @param left
	 * @param right
	 */
	public static void insert_sort(int[] A, int left, int right) {
		for (int p = left; p <= right; p++) {
			int tmp = A[p];
			int j;
			for (j = p; j > 0 && A[j - 1] > tmp; j--) {
				A[j] = A[j - 1];
			}
			A[j] = tmp;
		}

	}

	public static void swap(int[] A, int i, int j) {
		int x = A[i];
		A[i] = A[j];
		A[j] = x;
	}

	/**
	 * pick the second large number from A[left], A[center],A[right]
	 * 
	 * @param A
	 * @param left
	 * @param right
	 * @return
	 */
	public static int median(int[] A, int left, int right) {
		int center = (left + right) / 2;
		if (A[left] > A[center])
			swap(A, left, center);
		if (A[left] > A[right])
			swap(A, left, right);
		if (A[center] > A[right])
			swap(A, center, right);
		swap(A, center, right - 1);
		return A[right - 1];

	}

	public static void qsort(int[] A, int left, int right) {
		if (left + cutoff <= right) {
			int pivot = median(A, left, right);
			int i = left;
			int j = right - 1;
			for (;;) {
				while (A[++i] < pivot) {
				}
				while (--j > pivot) {
				}
				if (i < j) {
					swap(A, i, j);
				} else
					break;
			}
			swap(A, i, right - 1);
			qsort(A, left, i - 1);
			qsort(A, i + 1, right);
		} else {
			insert_sort(A, left, right);
		}
	}

	public static void main(String[] args) {
		int[] a = { 45, 23, 12, 56, 67, 43, 37, 101, 10 };
		qsort(a, 0, a.length - 1);
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}

}


转载于:https://www.cnblogs.com/bingtel/p/4194447.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值