快速排序

快速排序是基于分治策略的一种排序算法。基本思想是对输入的数组z[left, right] 按以下2个步骤进行排序:

1)分解: 以 a[left] 为基准元素,将a[left,right] 划分为3段, a[left, q-1], a[q], a[q+1, right],  使得a[left, q-1]中的任何元素都小于等于a[q], a[q+1, right]中任何元素都大于等于 a[q]; q在划分过程中确定;

2)递归求解: 对a[left, q-1],  a[q+1, right] 分别进行排序;a[left, q-1],  a[q+1, right]的排序都是就地完成的;

对《算法设计与分析》第四版 P31代码改进成可运行程序。

package ch02.book;

public class QuickSort {

	static boolean debug = true;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] arr = {11,38,65,97,76,13,27,49};
		System.out.print("Before sort: ");
		displayArray(arr);
		
		qSort(arr, 0, arr.length-1);
		System.out.print("After sort: ");
		displayArray(arr);
	}

	public static void displayArray(int[] arr) {
		if (debug) {
			for (int i = 0; i < arr.length; i++) {
				System.out.printf("%4d", arr[i]);
			}
			System.out.println();
		}
	}

	public static void qSort(int[] arr, int left, int right) {
		if (debug) System.out.printf("sort sub-arr [%d, %d]\r\n", left, right);
		
		if (left< right) {
			int interm = partition(arr, left, right);
			qSort(arr, left, interm-1);
			qSort(arr, interm + 1, right);
		}
	}
	public static int partition(int[] arr,int interm, int right) {
		if (debug) System.out.printf("partition for  sub-arr[ %d,  %d]\r\n", interm, right);
		
		int low = interm, high = right + 1 ;
		int flag = arr[interm];
		//int flag = arr[right];
		while(low < high) {
			while(arr[++low] < flag && low <right) ;
			while (arr[--high] > flag  );
			// find elements that satisfy: arr[low]>= flag and arr[high] <= flag;
			// then switch these two elements;
			if (low >= high) {
				break;
			}
			
			if (debug) System.out.printf("find arr[%d]:%d >= arr[%d]:%d >= arr[%d]:%d, exchange arr[%d] and arr[%d]:\r\n", low, arr[low],interm,arr[interm], high, arr[high], low, high);
			int temp = arr[low];
			arr[low] = arr[high];
			arr[high]= temp;
			displayArray(arr);
		}
		if (debug) {
			System.out.printf("partition complete , exchange arr[%d]: %d and arr[%d]:%d\r\n", interm, arr[interm], high, arr[high]);
		}
		arr[interm] = arr[high];
		arr[high]= flag;
		displayArray(arr);
		if (debug) System.out.printf("get interim %d\r\n", high);
		
		return high;
	}
}

测试数据运行结果:

Before sort:   11  38  65  97  76  13  27  49

After sort:   11  13  27  38  49  65  76  97

通过开启debug标志位可以观察排序的过程;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曼车斯基

如果内容对你有用,赏杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值