快速排序

 * 快速排序
 * 一、快速排序的思想
 * 快速排序通过将一个数组划分成俩个子数组,然后通过递归调用自身为每一个子数组进行快速排序来实现
 * 二、如何进行划分
 * 设定关键字,将比关键字小的放在一组,比关键字大的放在另一组
 * 三、如何自动设定关键字
 * 设置数组最右端的数据为关键字

 

package com.algorithm;

/**
 * 快速排序
 * 一、快速排序的思想
 * 快速排序通过将一个数组划分成俩个子数组,然后通过递归调用自身为每一个子数组进行快速排序来实现
 * 二、如何进行划分
 * 设定关键字,将比关键字小的放在一组,比关键字大的放在另一组
 * 三、如何自动设定关键字
 * 设置数组最右端的数据为关键字
 * @author lenovo
 *
 */
public class QuickSort {

	/**
	 * 划分数组
	 */
	public static int partition(long attr[],int left,int right,long point){
		int leftPtr= left-1;
		int rightPrt = right +1;
		while (true) {
			//循环,比关键字小的留在左端
			while (leftPtr < rightPrt &&  attr[++leftPtr]<point) ;
			//将比关键字大的留在右边,
			while (rightPrt > leftPtr &&  attr[--rightPrt]>point) ;
			if(leftPtr >= rightPrt){
				break;
			}else{
				long temp = attr[leftPtr];
				attr[leftPtr] = attr[rightPrt];
				attr[rightPrt] =temp;
			}
		}
		
		//将关键字和当前leftPtr所指的这一个进行交换
		long tmp = attr[leftPtr];
		attr[leftPtr] =  attr[right];
		attr[right] = tmp;
		return leftPtr;
	}
	
	public static void sort(long[] arr, int left, int right) {
		if(right - left <= 0) {
			return;
		} else {
			//设置关键字
			long point = arr[right];
			//获得切入点,同时对数组进行划分
			int partition = partition(arr, left, right, point);
			//对左边的子数组进行快速排序
			sort(arr,left,partition - 1);
			//对右边的子数组进行快速排序
			sort(arr,partition + 1, right);
		}
	}
	
	public static void displayArr(long attr[]){
		System.out.print("[");
		for(long num : attr) {
			System.out.print(num + " ");
		}
		System.out.print("]");
		System.out.println();
	}
	
	public static void main(String[] args) {
		long[] attr = new long[10];
		
		for (int i = 0; i < 10; i++) {
			attr[i] = (long) (Math.random()*99);
		}
		displayArr(attr);
		
		sort(attr, 0, attr.length - 1);
		displayArr(attr);
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值