数据库结构算法四:快速排序

/**
 * 快速排序(Quicksort)是对冒泡排序的一种改进。
 * 由C. A. R. Hoare在1962年提出。
 * 它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,
 * 其中一部分的所有数据都比另外一部分的所有数据都要小,
 * 然后再按此方法对这两部分数据分别进行快速排序,
 * 整个排序过程可以递归进行,以此达到整个数据变成有序序列。
 * @author gulijiang
 *
 */
public class Quicksort {
	static int i = 0;
	
	public static void main(String[] args) {
		int[] a = {49, 38, 65, 97, 76, 13, 27};
		sort(a, 0, a.length-1);
	}
	
	
	public static void sort(int[] a,int low,int high){
		if(low >= high)
		{
			return;
		}
		//完成一次单元排序
		int index = sortUnit(a, low, high);
		//对左边单元进行排序
		sort(a, low, index - 1);
		//对右边单元进行排序
		sort(a, index + 1, high);
	}
		
	
	
	public static int  sortUnit(int[] a,int low,int high){
		//记录次数
		i++;
		
		int key = a[low];
		
		while (low < high) {
			
			//从后向前搜索比key小的值
			while (a[high] >= key && high > low) {
				
				high --;
				
			}
			
			//比key小的放左边
		     if(low < high){ 
		    	int temp = a[low]; 
		        a[low] = a[high]; 
		        a[high] = temp; 
		        low++; 
		     }
			
			//从向前搜索比key大的值
			while (a[low] <= key && high > low) {
				
				low ++;
				
			}
			if(low < high){
				int temp = a[low]; 
		        a[low] = a[high]; 
		        a[high] = temp; 
		        high--; 
			}
			
		}
		
		System.out.println("第"+i+"趟排序完");
		for (int j = 0; j < a.length; j++) {
			System.out.print(a[j] +" ");
		}
		System.out.println("\n");
		
		return high;
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值