[Java]快速排序算法的Java实现

最近想学点分类算法,在写决策树算法的时候对于连续变量要先进行排序,于是就自己先写了一个快排的算法。思路照着百度百科上的C语言版本学的,但是由于java中没有指令的存在,所以必须要在一些方面做些变通,修改了异常处理模块,并增加了一个合并两个字符串的函数。

public class QuickSort{
    /**
     * 快速排序
     * @author Multiangle from Southeast University
     */
    public static void main(String[] args){

        int[] a={5,1,3,4,6,13,4,12,9,12,7,5,7,1,11} ;
        int[] rs=Sort(a,0,a.length-1) ;
        for(int i=0;i<rs.length;i++){
            System.out.print(rs[i]+"   ");
        }

    }

    public static int[] Sort(int[] input,int low,int high){
        System.out.println("进行 "+low+" 到 "+high+" 的排序") ;

        if(low>=high) return null ; //这一段处理元素调动
        int first=low ;
        int last=high ;
        int key=input[low] ;
        while(first<last){
            while((first<last)&&(input[last]>=key)) --last ;
            input[first]=input[last] ;
            while((first<last)&&(input[first]<=key)) ++first ;
            input[last]=input[first] ;
        }
        input[first]=key ;

        int[] res1,res2 ;   //这一段处理异常情况

        if (first-1>low) {
            res1=Sort(input,low,first-1) ;
        }else if(first-1==low) {
            int[] temp={input[low]} ;
            res1=temp ;
        }else{
            res1=null ;
        }

        if(high>first+1){
            res2=Sort(input,first+1,high) ;
        }else if(high==first+1){
            int[] temp={input[high]} ;
            res2=temp ;
        }else{
            res2=null ;
        }

        int[] finalres ;
        finalres=Combine(res1,res2,key) ;

        return finalres ;
    }

    private static int[] Combine(int[] res1,int[] res2,int key){
        int len1,len2 ;
        if(res1==null) len1=0 ;
        else len1=res1.length ;
        if(res2==null) len2=0 ;
        else len2=res2.length ;

        int[] res=new int[len1+len2+1] ;
        int index=0 ;
        for(int i=0;i<len1;i++) res[index++]=res1[i] ;
        res[index++]=key ;
        for(int i=0;i<len2;i++) res[index++]=res2[i] ;
        return res ;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值