1、写好划分函数(无论是否递归,这个函数都得有)
2、利用java中的stack对象存储划分的开始节点和结束节点,每次划分完存一次,再取出来划分。
利用stack完成递归的方法
public void nonRecrutQuickSort(int a[]){
if(a==null||a.length<=0)return;
Stack<Integer> index=new Stack<Integer>();
int start=0;
int end=a.length-1;
int pivotPos;
index.push(start); //存进去划分节点
index.push(end);
while(!index.isEmpty()){
end=index.pop(); //取出来
start=index.pop();
pivotPos=partition(a,start,end);
if(start<pivotPos-1){
index.push(start); //再存
index.push(pivotPos-1);
}
if(end>pivotPos+1){
index.push(pivotPos+1); //再存
index.push(end);
}
}
}
划分方法,体现了快排思想,把比标志位大的都放到一边,小的也放到另一边
public int partition(int[] a,int start,int end){//分块方法,在数组a中,对下标从start到end的数列进行划分
int pivot=a[start];
while(start<end){
while(start<end&&a[end]>=pivot) { //从末尾往前排查到第一个比pivot小的数
end--;
}
a[start]=a[end];
while(start<end&&a[start]<=pivot) {//从开头往后排查到第一个比pivot大的数
start++;
}
a[end]=a[start];
}
a[start]=pivot;
return start;//返回划分后的pivot的位置 ,这里start和end一定相等
}