非递归实现时借助栈,
package sort;
import java.util.Stack;
public class Sort
{
/*
* 非递归版本*/
public void quick2(int[] array){
if (array == null || array.length == 1) return ;
//存放开始与结束索引
Stack<Integer> s = new Stack<Integer>();
//压栈
s.push(0);
s.push(array.length - 1);
while (!s.empty()) {
int right = s.pop();
int left = s.pop();
//如果最大索引小于等于左边索引,说明结束了
if (right <= left) continue;
int i = partition(array, left, right);
if (left < i - 1) {
s.push(left);
s.push(i - 1);
}
if (i + 1 < right) {
s.push(i+1);
s.push(right);
}
}
//*************找到中轴位置***********//
public int partition(int[] a,int start,int end)
{
if (start<end)
{
int x = a[end];
int i = start-1;
for (int j = start; j < end; j++)
{
if (a[j]<=x)
{
i++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}else {
}
}
a[end] = a[i+1];
a[i+1] = x;
return i+1;//返回中轴位置
}
return 0;
}
//*********测试**********//
public static void main(String[] args)
{
int []a ={5,1,4,2,3};
Sort Sort = new Sort();
Sort.quick2(a);
for (int i : a)
{
System.out.println(i);
}
}
}