Java数据结构之快速排序

前言

     快速排序是面试中非常常见的排序算法,工作中,快速排序的效率也是我们常常用到的,他的发展来源于划分算法,采用的是分治策略.


实现思路

  1.     先从数组中选择一个pivot,
  2.     遍历数组,讲数组中比pivot大的数放到其右边,比其小的放到左边,
  3.     直到各区数组长度为1之前,都回到1处执行

具体说明

如上所示,我们先选择数组中第一个数49作为pivot,在第一次划分之后,会发现数组发生了变化,就是所有比pivot大的在右边,小的在左边

然后递归调用子数组划分,直到子数组长度为1.

代码实现

package com.example.liner;


public class QuickSort {

	//
	public static int theArr[]=new int []{13,2,4,1,22,31,5,7,8,9,15,17};
	public static int partition=10;
	
	public static int partitionitSort(int leftPar,int rightPar,int pivot){
		int left=leftPar-1;
		int right=rightPar;
		
		while(true){
			while(
					theArr[++left]<pivot)
				;
			
			while(
					theArr[--right]>pivot)
				;
			
			if(left>=right){
				break;
			}else{
				swap(left, right);
			}
			
		}
		swap(left, rightPar);
		return left;
	}
			
		
	
	public static void display(){
		
		for(int i=0;i<theArr.length;i++){
			System.out.print(theArr[i]+" ");
		}
	}
	
	public static void ruicksout(int left,int right){
		if(right-left<=0){
			return;
		}else{
			int pivot=theArr[right];
			
			int par=partitionitSort(left, right, pivot);
			ruicksout(left, par-1);
			ruicksout(par+1,right);
			
		}
	}
	
	
	public static void swap(int a,int b){
		int temp;
		temp=theArr[a];
		theArr[a]=theArr[b];
		theArr[b]=temp;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ruicksout(0, theArr.length-1);
		
		display();
	}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值