java stack快排

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一定相等
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值