zoukankan      html  css  js  c++  java
  • Algs4-2.1.11希尔排序序列改为存数组

    2.1.11将希尔排序中实时计算递增序列改为预先计算并存储在一个数组中。
    public class Shell2
    {
        public static void sort(Comparable[] a)
        {
            int N=a.length;
            int h=1;
            int[] SN=new int[20];
            int hMaxIndex=0;
            while (h<N/3)
            {
               SN[hMaxIndex]=h;
                h=3*h+1;
                hMaxIndex++;
            }

           
            for (int hIndex=hMaxIndex;hIndex>0;hMaxIndex--)
            {
                h=SN[hIndex];
                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=0;i<a.length;i++)
                if(less(a[i],a[i-1])) return false;
            return true;
        }
       
      
    }

  • 相关阅读:
    最长上升子序列问题
    多重部分和问题 (dp)
    01背包问题的延伸即变形 (dp)
    完全背包问题入门 (dp)
    最长公共子序列问题
    01背包入门 dp
    POJ 30253 Fence Repair (二叉树+优先队列)
    POJ 3069 Saruman's Army (模拟)
    [leetcode-357-Count Numbers with Unique Digits]
    [leetcode-474-Ones and Zeroes]
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860018.html
Copyright © 2011-2022 走看看