package cn.ccnu.lzc;
import java.util.Random;
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int maxSize=16;
ArrayIns arr=new ArrayIns(maxSize);
for(int i=0;i<maxSize;i++){
int n=new Random().nextInt(100);
arr.insert(n);
}
arr.display();
arr.quickSort();
arr.display();
}
}
class ArrayIns{
private int[] theArray;
private int nElems;
//初始化数组
public ArrayIns(int max){
this.theArray=new int[max];
this.nElems=0;
}
//向数组中插入数据
public void insert(int value){
theArray[nElems++]=value;
}
//打印数组
public void display(){
for(int i:theArray){
System.out.print(i+" ");
}
System.out.println();
}
//快速排序,选取数组最后一个为关键字
public void quickSort(){
recQuickSort(0,nElems-1);
}
public void recQuickSort(int left,int right){
if(left>=right){
return;
}
int pivot=theArray[right];
int partition=partitionIt(left,right,pivot);
recQuickSort(left,partition-1);
recQuickSort(partition+1,right);
}
//求得最终关键字的位置
private int partitionIt(int left,int right,int pivot){
int leftptr=left-1;
int rightptr=right;
while(true){
while(theArray[++leftptr]<pivot); //这里不需要进行越界检测,因为leftptr最后不可能越过关键字
while(rightptr>0&&theArray[--rightptr]>pivot);
if(leftptr>=rightptr){
break;
}else{
swap(leftptr,rightptr);
}
}
swap(leftptr,right);
return leftptr;
}
private void swap(int leftptr, int rightptr) {
// TODO Auto-generated method stub
int temp=theArray[leftptr];
theArray[leftptr]=theArray[rightptr];
theArray[rightptr]=temp;
}
}