java之快速排序

java之快速排序

直接上代码:
-----------------------------------------------------
package com.mylearn;

/**
 * 快速排序法,基本思想:选择一个基准元素,通常选择第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于等于基准元素
 * ,此时基准元素在其排好序后的正确位置,然后再用同样的方法递归地排序划分的两部分。
 * 
 * @author H
 *
 */
public class KuaiSu {

	// 快速排序主程序
	public static void kuaisu(int[] arr) {
		quickSort(arr, 0, arr.length - 1);
	}

	// 快速排序法递归,表明要排序的数组,以及起始索引
	private static void quickSort(int[] arr, int first, int last) {
		// 只要最后一个大于第一个的索引
		if (last > first) {
			// 将数组分为两部分,并且选择第一个为主元
			int pivotIndex = partition(arr, first, last);
			// 对主元分开的两个子数组进行排序
			quickSort(arr, first, pivotIndex - 1);
			quickSort(arr, pivotIndex + 1, last);
		}
	}

	// 寻找主元并且划分数组的部分
	public static int partition(int[] list, int first, int last)// 划分数组为两部分
	{
		// 选择第一个为主元
		int pivot = list[first];
		// 后面将数组划分为大于主元和小于主元的两大块
		int low = first + 1;
		int high = last;

		// 如果high大于low
		while (high > low) {
			// 如果low的元素小于pivot就继续推进
			while (low <= high && list[low] <= pivot)
				low++;
			// 如果high的元素大于pivot就继续后退
			while (low <= high && list[high] > pivot)
				high--;
			// 否则,说明出现了相反情况,则交换两个元素
			if (high > low)// 当list[high]
    
    
     
      first && list[high] >= pivot)
			high--;
		// 如果一开始选的主元比最后一个high元素要大
		if (pivot > list[high]) {
			list[first] = list[high];
			list[high] = pivot;
			return high;
		} else
			return first;
	}

	public static void main(String[] args) {
		// 声明数组
		int[] arr = { 1, 2, 3, 0, 1, 5, -1, 2 };
		// 调用快速排序算法
		kuaisu(arr);
		// 输出结果
		for (int element : arr)
			System.out.println(element);

	}
}
    
    

------------------------------------------------------------------------------------------------------------------------------------

更多请关注:FlyTester,关注技术的测试

QQ群:456850134

web站:www.flytester.org

微信扫描二维码关注:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值