快速排序(递归实现)

/*
 * 快速排序算法  用到了 <分治法>《递归算法》
 */
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; // 返回枢轴元素位置
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值