交换类排序——快速排序

参考:

https://download.csdn.net/download/qq_31567335/10356263

快速排序理解:

快速排序是将分治法运用到排序问题中的一个典型例子,快速排序的基本思想是:通过一个枢轴(pivot)元素将 n 个元素的序列分为左、右两个子序列 Ll Lr,其中子序列 Ll中的元素均比枢轴元素小,而子序列 Lr 中的元素均比枢轴元素大,然后对左、右子序列分别进行快速排序,在将左、右子序列排好序后,则整个序列有序,而对左右子序列的排序过程直到子序列中只包含一个元素时结束,此时左、右子序列由于只包含一个元素则自然有序。

 

划分过程:

1.待划分元素范围为low-high,取 low 所指元素为枢轴,即 pivot = r[low] 。

2.从high向下查找比pivot小的元素,插入low的位置。

3.从low向上查找比pivot大的元素,插入high的位置。

4,步骤2,3交替进行。当low==high的时候,划分结束。

可以理解为:

当移动high进行查找的时候,待划分的元素为low+1——high,位置low是待插入位置

当移动low进行查找的时候,待划分的元素为low——high-1,位置high是待插入位置。

所以说如果当low向上移动或high向下移动到low==high的时候,没有元素需要划分,划分过程结束,将pivot插入此位置即可。

package dataStructureAndAlgorithms;

public class SwapSort_quickSort {

	public static void sort(int[] array, int low, int high) {
		if (low < high) {
			int pa = partition(array, low, high);
			sort(array, low, pa - 1);
			sort(array, pa + 1, high);
		}
	}

	public static int partition(int[] array, int low, int high) {
		// 确定枢轴元素
		int pivot = array[low];
		while (low < high) {
			// 从高向低寻找比pivot小的元素
			while (low < high && array[high] >= pivot) {
				high--;
			}
			array[low] = array[high];

			// 从低向高寻找比pivot大的元素
			while (low < high && array[low] <= pivot) {
				low++;
			}
			array[high] = array[low];
		}
		array[low] = pivot;
		return low;
	}

	public static void display(int[] array) {
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
		System.out.println();
	}

	public static void main(String args[]) {
		int[] array = { 4, 2, 8, 9, 5, 7, 6, 1, 3 };
		// 未排序数组顺序为
		System.out.println("未排序数组顺序为:");
		display(array);
		System.out.println("-----------------------");
		sort(array, 0, array.length - 1);
		System.out.println("-----------------------");
		System.out.println("经过快速排序后的数组顺序为:");
		display(array);
	}

}

 

输出:

未排序数组顺序为:
4 2 8 9 5 7 6 1 3 
-----------------------
-----------------------
经过快速排序后的数组顺序为:
1 2 3 4 5 6 7 8 9 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值