zoukankan      html  css  js  c++  java
  • 算法(第四版)学习笔记之java实现希尔排序

    希尔排序思想:使数组中随意间隔为h的元素都是有序的。

    希尔排序是插入排序的优化。先对数组局部进行排序,最后再使用插入排序将部分有序的数组排序。

    代码例如以下:

    /**
     * 
     * @author seabear
     *
     */
    
    public class ShellSort {
    	public static void sort(Comparable[] a)
    	{
    		int N = a.length;
    		int h = 1;
    		while(h < N/2)
    		{
    			h = 4 * 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)
    				{
    					int n = j - h;
    					System.out.println(j + ":" + a[j] + "," + n + ":" + a[j-h]);
    					exch(a,j,j-h);
    					show(a);
    				}
    			}
    			h = h / 4;
    		}
    	}
    	
    	public static boolean less(Comparable v,Comparable w)
    	{
    		return v.compareTo(w) < 0;
    	}
    	
    	public static void exch(Comparable[] a,int i,int j)
    	{
    		Comparable temp = a[i];
    		a[i] = a[j];
    		a[j] = temp;
    	}
    	
    	public static boolean isSort(Comparable[] a)
    	{
    		for(int i = 1; i < a.length; i++)
    		{
    			if(less(a[i],a[i-1]))
    			{
    				return false;
    			}
    		}
    		return true;
    	}
    	
    	public static void show(Comparable[] a)
    	{
    		for(int i = 0; i < a.length; i++)
    		{
    			System.out.print(a[i] + " ");
    		}
    		System.out.println();
    	}
    	
    	public static void main(String[] args)
    	{
    		Integer[] a = new Integer[10];
    		for(int i = 0; i < 10; i++)
    		{
    			a[i] = (int)(Math.random() * 10 + 1);
    			System.out.print(a[i] + " ");
    		}
    		System.out.println();
    		sort(a);
    		show(a);
    	}
    }
    


  • 相关阅读:
    【一些思路】web和app测试的区别
    【Python】I/O和比赛的其他一些问题
    【Python】迭代器和生成器的个人理解,再讲一讲协程
    【TCP/IP】如果打不开一个网页,需要如何处理?
    DOM事件
    GASP动画的基本使用
    Velocity的使用方法
    Swiper和Swiper Animate使用方法
    DOM操作
    JavaScript函数
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6732930.html
Copyright © 2011-2022 走看看