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

2.1.11

时间:2018-05-29 20:40:48      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:rgs   array   sorted   color   seq   bool   import   com   OLE   

question:

Implement a version of shellsort that keeps the increment sequence in an array, rather than computing it;

answer:

import edu.princeton.cs.algs4.*;

public class Shell
{
    public static void sort(Comparable[] a)
    {
        int N = a.length;
        int h = 1;
        while(h < N/3) h = 3*h + 1;
        
        int increment[] = new int[N];//存放h
        increment[0] = h;
        for(int t = 1; t < N && h>=1; t++)
        {
            increment[t] = increment[t-1]/3;
        }
        
        for(int t = 0; t < increment.length; t++)
        {
            h = increment[t];
            for(int i = h; i < N; i++)
            {
                for(int j = i; j >= h && less(a[j],a[j-h]); j-=h)
                    exch(a,j,j-h);
            }
        }
    }
    
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void exch(Comparable[] a, int i, int j)
    {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    
    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 main(String[] args)
    {
        String[] a = In.readStrings();//CTRL + d
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

 

2.1.11

标签:rgs   array   sorted   color   seq   bool   import   com   OLE   

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

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