原理是将开始与结束的索引放入栈中,然后取栈中的数据段排序。
public class QuickStart {
public static void main(String[] args) {
int[] arr = {5,8,3,9,1,2,7,4,6};
quickSort(arr);
for(int i:arr)
System.out.print(i+" ");
}
public static void quickSort(int[] arr){
Stack<Left_Right> stack = new Stack<Left_Right>();
stack.push(new Left_Right(0, arr.length-1));
while(!stack.isEmpty()){
Left_Right pop = stack.pop();
int half = toHalf(arr, pop.left, pop.right);
if((half+1)<pop.right)
stack.push(new Left_Right(half+1, pop.right));
if((half-1)>pop.left)
stack.push(new Left_Right(pop.left,(half-1)));
}
}
public static int toHalf(int[] arr,int left,int right){
int pivot = arr[right];//得到枢轴
while (left<right) {
//左边开始找比枢轴大的
while (arr[left]<=pivot&&left<right)
left++;
//找到左边比枢轴大的,扔到右边去
if(left<right){
arr[right]=arr[left];
right--;
}
while(arr[right]>=pivot&&left<right)
right--;
//找到右边的比枢轴小的扔到左边去
if(left<right){
arr[left]=arr[right];
left++;
}
}
arr[left]=pivot;
return left;
}
}
class Left_Right{
int left;
int right;
public Left_Right(int left,int right){
this.right = right;
this.left = left;
}
}
转载自原文链接, 如需删除请联系管理员。
原文链接:快速排序(非递归实现),转载请注明来源!