Data Structures and Algorithms-快速排序(个人java实现)

package Sort;

public class QuickSort {
	/*
	 * 快排思路:找到1个基准值,然后进行一次(左右指针的判断)最后保证基准值左边都比基础值小,
	 * 基准值右边都比基准值大,然后在对左右两边继续递归重复这个过程
	 */
	public void display(int[] array){  
	       for(int i=0;i<array.length;i++){  
	          System.out.print(array[i]+"\t");  
	       }  
	       System.out.println();  
	} 
	
	public void quicksort(int[] array){
		diguiSort(0,array.length-1,array);
	}
	
	public void diguiSort(int low,int high,int[] array){
		if(low>=high){
			return;
		}else{
			//标准值
			int model = array[low];
			int index = partion(model,low,high,array);
			display(array);
			//这里的index位置的数值已经是合适的位置,所以一下递归的方法上下限都相应-1或者+1
			diguiSort(low,index-1,array);
			diguiSort(index+1, high, array);
		}
	}

	private int partion(int model, int low, int high,int[] array) {
		//这里的边界条件是重点
		while(low<high){
			/* 注意注意!!!!这里array[high]>=model和下面的array[low]<=model的等号必须存在,为什么呢
			 * 因为最外面的while循环跳出的条件是low==high,如下例所示,有2个46,当最后递归,这个分区只有46两个元素,
			 * 这个时候high得不到--,low得不到++,low永远不等于high,我们在这里处于死循环
			 */
			while(low<high&&array[high]>=model){
				high--;
			}
			swap(low,high,array);
			while(low<high&&array[low]<=model){
				low++;
			}
			swap(high,low,array);

		}
		return low;
	}

	private void swap(int high, int low, int[] array) {
		int temp = array[high];
		array[high] = array[low];
		array[low] = temp;
	}
	
	public static void main(String[] args) {
		QuickSort sort = new QuickSort();
		int[] array = new int[]{456,784,49,2,37,46,123,53
				,126,465,656,7689,45,23,89,46,237};
		System.out.println("原始数组数据为");
		sort.display(array);
		sort.quicksort(array);

	}
	
}


测试数据如下:

原始数组数据为
456	784	49	2	37	46	123	53	126	465	656	7689	45	23	89	46	237	
237	46	49	2	37	46	123	53	126	89	23	45	456	7689	656	465	784	
45	46	49	2	37	46	123	53	126	89	23	237	456	7689	656	465	784	
23	37	2	45	49	46	123	53	126	89	46	237	456	7689	656	465	784	
2	23	37	45	49	46	123	53	126	89	46	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	126	89	123	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	126	89	123	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	126	89	123	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	123	89	126	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	89	123	126	237	456	7689	656	465	784	
2	23	37	45	46	46	49	53	89	123	126	237	456	784	656	465	7689	
2	23	37	45	46	46	49	53	89	123	126	237	456	465	656	784	7689	
2	23	37	45	46	46	49	53	89	123	126	237	456	465	656	784	7689	

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值