码迷,mamicode.com
首页 > 其他好文 > 详细

2.2.10

时间:2018-05-31 23:02:03      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:stdout   not   page   assert   show   iss   str   oid   fast   

question:

Faster merge. Implement a version of merge()  that copies the second half of a[] to aux[] in decreasing order and then does the merge back to a[]. This change allows you to remove the code to test that each of the halves kas been exhausted from the inner loop. Note: The resulting sort is not stable(see page 341).

answer:

//减少一个判断条件

 

import edu.princeton.cs.algs4.*;

public class Merge
{
    private static Comparable[] aux;
    
    public static void sort(Comparable[] a)
    {
        aux = new Comparable[a.length];
        sort(a, 0, a.length-1);
    }
    
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void show(Comparable[] a)
    {
        for(int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }
    
    public static boolean isSorted(Comparable[] a)
    {
        for(int i = 1; i < a.length; i++)
            if(less(a[i], a[i-1])) return false;
        return true;
    }
    
    public static void merge(Comparable[] a, int lo, int mid, int hi)
{
    int i = lo, j = hi;//注意这里j为hi
    
    int k;
    for(k = lo; k <= mid; k++)//复制前一半到aux里面
        aux[k] = a[k];
    
    for(int t = hi; t >= mid + 1;t--,k++)//复制后一半反向到aux里面
        aux[k] = a[t];
    
    for(int c = lo; c <= hi; c++)//把a[]填满就退出循环
    {
        //减少了一个判断条件
        //拿到边界时会出现aux[i] == aux[j],所以最后一次拿哪个都一样!
        if(less(aux[i], aux[j]))
            a[c] = aux[i++];
        else
            a[c] = aux[j--];
    }
}
    
    private static void sort(Comparable[] a, int lo, int hi)
    {
        if(hi <= lo)
            return;
        int mid = lo + (hi - lo) / 2;//不用(a+b)/2是因为a+b可能超过int的上界,防止溢出
        sort(a,lo,mid);//排左侧
        sort(a,mid+1,hi);//排右侧
        merge(a,lo,mid,hi);//归并
    }
    
    public static void main(String[] args)
    {
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

 

2.2.10

标签:stdout   not   page   assert   show   iss   str   oid   fast   

原文地址:https://www.cnblogs.com/w-j-c/p/9119352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!