快速排序算法——java语言

快速排序算法 基于划分和递归实现,以下是参考《数据结构和算法分析java语言描述》第三版 中的代码实现并结合自己的测试 编写的。

public class QuickSort { private static final int CUTOFF= 0; /** * quickSort algorithm * * @param a * an array of comparable<> * @param a */ public static <AnyType extends Comparable<? super AnyType>> void quicksort(AnyType[] a) { quicksort(a, 0, a.length - 1); }

/**
 * Internal quicksort method that makes recursive calls 
 * uses median-of-three pattitoning and a cutoff of 10 
 * [@param](https://my.oschina.net/u/2303379) a an array of Comparable items.
 * [@param](https://my.oschina.net/u/2303379)  left the left-most index of subarray
 * [@param](https://my.oschina.net/u/2303379)  right the right-most index of subarray 
 */		
private static <AnyType extends Comparable<? super AnyType>> void quicksort(AnyType[] a, int left, int right) {
	if(left+CUTOFF<=right &&right>0 ){
		AnyType pivot = median3(a, left, right);//找到分割点
		 
		//begin partitioning
		int i=left, j=right-1;
		
		for(;;){
			while(i<right-1&&a[i].compareTo(pivot)<0 ){i++;} // a[i] >= privot
			while(j>left&&a[j].compareTo(pivot)>0){j--;}	// a[j] <= privot
			if(i<j){
				swap(a, i, j);
			}else{
				break;
			}
		}
		
		swap(a, i, right);//restore pivot
		
		quicksort(a,left,i-1);//sort small elements
		quicksort(a,i+1,right);//sort larger elements			
	} else{//do an insertion  sort on the subarray

// insertionSort(); }

}

/**
 * return median of  left ,center ,and right
 * order these and hide the piovt
 * @param a
 * @param left
 * @param right
 * @return
 */
private static <AnyType extends Comparable<? super AnyType>> AnyType median3(AnyType[] a, int left, int right) {
	int center = (left + right) / 2;
	if (a[center].compareTo(a[left]) < 0)
		swap(a, center, right);
	if (a[right].compareTo(a[left]) < 0)
		swap(a, right, left);
	if (a[right].compareTo(a[center]) < 0)
		swap(a, right, center);

	// place piovt at position right-1
	//使枢纽元素离开被分割的段
	swap(a, center, right );
	return a[right];
}

private static <AnyType extends Comparable<? super AnyType>> void swap(AnyType[] a, int left, int right) {
	AnyType temp = a[left];
	a[left] = a[right];
	a[right] = temp;
}

}

//测试方法 public class TestApp { public static void main(String[] args) {

	Integer[] a = new Integer[16];
	for (int i = 0; i < 16; i++) {
		a[i]=(int)(Math.random()*100);
	}
	display(a);
	QuickSort.quicksort(a);
	display(a);
}

private static void display(Integer[] a) {
	 for (int i = 0; i < 16; i++) {
		System.out.print(a[i]+" ");
	}
	 System.out.println();
}

}

转载于:https://my.oschina.net/u/2485910/blog/869197

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值