美文网首页
算法(第四版)快速排序

算法(第四版)快速排序

作者: 博林木木 | 来源:发表于2016-11-25 17:23 被阅读0次

    写快排的时候遇到了不少困难,虽然只有几行代码
    得到的最重要的体会是左侧的指针(i)最终会在右侧的指针(j)的右边,也就是最终停止的时候j+1 = i(永远只会停到这里)
    参考了文章http://blog.csdn.net/kwang0131/article/details/51085734
    解释的很清晰

    package suanfa;
    
    import com.algs4.stdlib.StdOut;
    
    /**
     * Created by evan on 16/11/24.
     * 二分快速排序
     */
    
    public class quickSort {
    
        public static void main(String[] args){
    
            Integer[] papapa = {4,9,6,5,11,13,22,66};
            sort(papapa,0,papapa.length-1);
    
            for (Integer value:papapa) {
    
                StdOut.println(value);
            }
        }
    
        public static void sort(Comparable[] intList,int low, int high){
    
            if(low>=high){
                return;
            }
    
            int mid = partition(intList,low,high);
    
    
            sort(intList,low,mid-1);
            sort(intList,mid+1,high);
    
        }
    
        public static Boolean less(Comparable a, Comparable b){
    
            return a.compareTo(b) < 0;
    
        }
    
    
        public static int partition(Comparable[] a,int lo,int hi){
    
    
            int i = lo;
            int j = hi+1;
            Comparable v = a[lo];
            while (true){
    
                while(less(a[++i],v)){}
                while(less(v,a[--j])){}
    
                if (i >= j){
                    break;
                }
    
                exch(a,i,j);
            }
            
            exch(a,j,lo);
            return j;
        }
    
        public static void exch(Comparable[] intList,int low,int high){
            Comparable tmp = intList[low];
            intList[low] = intList[high];
            intList[high] = tmp;
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:算法(第四版)快速排序

          本文链接:https://www.haomeiwen.com/subject/avkwpttx.html