前言
快速排序是面试中非常常见的排序算法,工作中,快速排序的效率也是我们常常用到的,他的发展来源于划分算法,采用的是分治策略.
实现思路
- 先从数组中选择一个pivot,
- 遍历数组,讲数组中比pivot大的数放到其右边,比其小的放到左边,
- 直到各区数组长度为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();
}
}