快速排序(递归实现)

/*
 * 快速排序算法  用到了 <分治法>《递归算法》
 */
package com.xiahui;
public class QuickSort {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a = { 2, 19, 33, 4, 6, 9, 0 };
		QuickSort quickSort = new QuickSort();
		quickSort.quickSort(a, 0, 6);
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}
	public void quickSort(int[] r, int low, int high) {
		if (low < high) {
			int pa = partition(r, low, high);
			quickSort(r, low, pa - 1);// 递归算法
			quickSort(r, pa + 1, high);// 递归算法 一定要 特别精通
		}
	}
	private int partition(int[] r, int low, int high)// 传进来一个数组可以对任意两个下标之间进行快速排序
	{
		int pivot = r[low]; // 使用r[low]作为枢轴元素
		while (low < high) // 从两端交替向内扫描
		{
			while (low < high && r[high] > pivot) {  //从右往前扫描
				high--;
			}
			r[low] = r[high]; // 将比pivot 小的元素移向低端
			while (low < high && r[low] < pivot) {
				low++;
			}
			r[high] = r[low]; // 将比pivot 大的元素移向高端
		}
		r[low] = pivot; // 设置枢轴
		return low; // 返回枢轴元素位置
	}
}


你可能感兴趣的:(快速排序)