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

2.2.2

时间:2018-05-31 16:45:38      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:OLE   void   显示   归并   print   block   nbsp   top   span   

question:

Give traces, in the style of the trace given with ALGORITHM 2.4, showing how the keys E A S Y Q U E S T I O N are sorted with top-down mergesort.

answer:

import edu.princeton.cs.algs4.*;

public class Merge
{
    private static Comparable[] aux;
    
    public static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    public static void merge(Comparable[] a, int lo, int mid, int hi)
    {
        int i = lo;
        int j = mid + 1;
        for(int k = lo; k <= hi; k++)
            aux[k] = a[k];
        for(int k = lo; k <= hi; k++)
        {
            if(i > mid)
                a[k] = aux[j++];
            else if(j > hi)
                a[k] = aux[i++];
            else if(less(aux[j], aux[i]))
                a[k] = aux[j++];
            else
                a[k] = aux[i++];
        }
    }
    
    public static void sort(Comparable[] a)
    {
        aux = new Comparable[a.length];
        sort(a, 0, a.length-1);
    }
    
    public static void sort(Comparable[] a, int lo, int hi)
    {
        if(hi<=lo)
            return;
        int mid = lo + (hi - lo)/2;
        sort(a,lo,mid);
        sort(a,mid+1,hi);
        merge(a,lo,mid,hi);
        show(a,lo,hi);//每次归并完后显示归并的元素
    }
    
    public static void show(Comparable[] a, int lo, int hi)
    {
        for(int i = 0; i < lo; i++)
        {
            StdOut.print("  ");
        }
        for(int i = lo; i <= hi; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }
    
    public static void main(String[] args)
    {
        //输入E A S Y Q U E S T I O N
        String[] a = In.readStrings();
        sort(a);
    }
}

 

2.2.2

标签:OLE   void   显示   归并   print   block   nbsp   top   span   

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

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