单向扫描快排,双向扫描快排与非递归快排

import java.util.Stack;


public class QuickSort {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int unsort[]={4,3,5,6,2,1},i;
quickSort3(unsort,0,5);
for(i=0;i<6;i++)
System.out.print(unsort[i]+",");
}

//单向扫描快排
static void quickSort(int p[],int left,int right){
int i,j,x,temp,k;
if(left<right){
i=left-1;
x=p[right];
for(j=left;j<right;j++){
if(p[j]<=x){
i++;
temp=p[i];p[i]=p[j];p[j]=temp;
}
}
temp=p[i+1];p[i+1]=x;p[right]=temp;
quickSort(p,left,i);
quickSort(p,i+2,right);
}
}

//双向扫描快排
static int partition(int p[],int left,int right){
int temp=p[left];
while(left<right){
while(left<right&&p[right]>=temp)
right--;
p[left]=p[right];
while(left<right&&p[left]<=temp)
left++;
p[right]=p[left];
}
p[left]=temp;
return left;
}
static void quickSort2(int p[],int left,int right){
int mid;
if(left<right){
mid=partition(p,left,right);
quickSort2(p,left,mid-1);
quickSort2(p,mid+1,right);
}
}

//非递归快排
static void quickSort3(int p[],int left,int right){
int mid;
Stack<Integer> stack=new Stack<Integer>();
if(left<right){
mid=partition(p,left,right);
if(left<mid-1){
stack.push(left);
stack.push(mid-1);
}
if(right>mid+1){
stack.push(mid+1);
stack.push(right);
}
while(!stack.empty()){
int high=stack.pop();
int low=stack.pop();
mid=partition(p,low,high);
if(low<mid-1){
stack.push(low);
stack.push(mid-1);
}
if(high>mid+1){
stack.push(mid+1);
stack.push(high);
}
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值