• Algs4-2.1.9给出希尔排序的轨迹


     2.1.9按照算法2.3所示轨迹的格式给出希尔排序是如何将数组 E A S Y S H E L L S O R T Q U E S T I O N排序的。
    答:灰底色表示相关元素未互换,黄底色表示相关元素互换。1-sort省略,与插入排序相同。

    图片

    图片
    图片
    public class Shell
    {
        public static void sort(Comparable[] a)
        {
            int N=a.length;
            int h=1;
            while (h<N/3) h=3*h+1;
            while (h>=1)
            {
                for (int i=h;i<N;i++)
                {
                 //   for (int j=i;j>=h && less(a[j],a[j-h]);j-=h)
                     for (int j=i;j>=h ;j-=h)
                    {
                       if(h>1) StdOut.printf("h=%-5d i=%-5d j=%-5d ",h,i,j);
                        if( less(a[j],a[j-h]))   exch(a,j,j-h);
                    }
                }
                h=h/3;
            }
        }
       
        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;
        }
       
        public static void main(String[] args)
        {
            String[] a={"E","A","S","Y","S","H","E","L","L","S","O","R","T","Q","U","E","T","I","O","N"};
            sort(a);
        }
      
    }

  • 相关阅读:
    专为seo新手准备的百度分享工具教程
    什么是关键词权重
    什么是关键词堆砌
    什么是目标关键词
    华为SEO搜索引擎主管招聘内容
    长尾关键词是什么意思
    Java面试宝典(7)混合2
    SpringMVC学习(5):数据绑定2 @PathVariable、@CookieValue、@RequestHeader、@ModelAttribute..
    MyBatis中XML 映射配置文件的简单介绍
    最牛B的编码套路
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9860015.html
Copyright © 2020-2023  润新知