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

2.2.9

时间:2018-05-31 22:00:01      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:ble   a+b   pre   col   public   OLE   hint   不用   main   

question:

Use of a static array like aux[] is inadvisable in library software because multiple clients might use the class concurrently. Give an implementation of Merge that does not use a static array. Do not make aux[] local to merge() (see the Q&A for this section). Hint: Pass the auxiliary array as an argument to the recursive sort().

answer:

import edu.princeton.cs.algs4.*;

public class Merge
{
    
    public static void sort(Comparable[] a)
    {
        Comparable[] aux = new Comparable[a.length];//只调用单参数sort一次,所以此aux只创建一次,之后传参就行
        sort(a, 0, a.length-1, aux);
    }
    
    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, Comparable[] aux)
{
    int i = lo, j = mid + 1;
    
    for(int k = lo; k <= hi; k++)//复制
        aux[k] = a[k];
    
    for(int k = lo; k <= hi; k++)//把a[]填满就退出循环
    {
        if(i > mid)//左侧已用完,则只能从右侧拿
            a[k] = aux[j++];
        else if(j > hi)//右侧已用完,则只能从左侧拿
            a[k] = aux[i++];
        else if(less(aux[i], aux[j]))//当前左侧比右侧小,从右侧拿
            a[k] = aux[i++];
        else//反之当前右侧比左侧小,从左侧拿
            a[k] = aux[j++];
    }
}
    
    private static void sort(Comparable[] a, int lo, int hi, Comparable[] aux)
    {
        if(hi <= lo)
            return;
        int mid = lo + (hi - lo) / 2;//不用(a+b)/2是因为a+b可能超过int的上界,防止溢出
        sort(a,lo,mid, aux);//排左侧
        sort(a,mid+1,hi, aux);//排右侧
        merge(a,lo,mid,hi, aux);//归并
    }
    
    public static void main(String[] args)
    {
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

 

2.2.9

标签:ble   a+b   pre   col   public   OLE   hint   不用   main   

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

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