【排序算法】快速排序

快速排序的基本思想:

采用分治策略,每一趟排序把一个指定的元素放到合理的位置,满足其左边的元素全部比它小(大),其右边的元素全部比它大(小),每一趟排序,指定当前排序的范围,介于low和high之间

递归的结束标志是low<=high

具体看算法实现:

	public static void quickSort(int[] array,int low,int high){
		if(high<=low){
			return;
		}
		int index_low = low;
		int index_high = high;
		int cmp = array[index_low];
		while(low<high){
			while(array[high]>cmp&&low<high){
				high--;
			}
			while(array[low]<=cmp&&low<high){
				low++;
			}
			if(low<high){
				int temp = array[high];
				array[high] = array[low];
				array[low] = temp;
				for(int i:array){
					System.out.print(i+" ");
				}
				System.out.println("");
			}
			
		}
		int temp = array[low];
		array[low] = array[index_low];
		array[index_low] = temp;
		for(int i:array){
			System.out.print(i+" ");
		}
		System.out.println("");
		quickSort(array,index_low,low-1);
		quickSort(array,high+1,index_high);
	}

测试:

public class CommonTest {
	int[] array = {5,1,6,2,7,15,11,3,8,3,9,0};
	
	@Test
	public void testQuickSort(){		
		QuickSort.quickSort(array, 0, array.length-1);
	}
}


每一趟的排序输出:

5 1 0 2 7 15 11 3 8 3 9 6 
5 1 0 2 3 15 11 3 8 7 9 6 
5 1 0 2 3 3 11 15 8 7 9 6 
3 1 0 2 3 5 11 15 8 7 9 6 
3 1 0 2 3 5 11 15 8 7 9 6 
2 1 0 3 3 5 11 15 8 7 9 6 
0 1 2 3 3 5 11 15 8 7 9 6 
0 1 2 3 3 5 11 15 8 7 9 6 
0 1 2 3 3 5 11 6 8 7 9 15 
0 1 2 3 3 5 9 6 8 7 11 15 
0 1 2 3 3 5 7 6 8 9 11 15 
0 1 2 3 3 5 6 7 8 9 11 15 


快速排序这种东西,光是理解了思想还不行,还要自己手动写出来,写个一两遍,两三遍,三四遍,就差不多能记住了。

主要是递归结束标志和每一趟循环结束标志比较难理解。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值