`

希尔排序

阅读更多

      通过公式h=3*h+1生成间隔序列1,4,13,40,121,364……,使用中通过h=(h-1)/3减小间隔进行计算(也就是间隔依次为……,364,121,40,12,4,1)。

 

public class ShellSort 
{	
	public static void main(String[] args)
	{
		int[] array = new int[]{23, 6, 18, 20, 45, 31, 79, 3, 64, 82, 99, 1};
		
		Display(array, "Befor sort: ");
		
		Sort(array);
		
		Display(array, "After sort: ");
	}
	
	public static void Sort(int[] array)
	{
		int h = 0;
		int temp = 0;
		int index = 0;
		
		while(h < array.length)
			h = h*3 + 1;
		h = (h-1)/3;
		
		while(h>0)
		{			
			for(int i=h; i<array.length; i++)
			{
				temp = array[i];
				index = i;
				
				while(index > h-1 && array[index-h] >= temp)
				{
					array[index] = array[index-h];
					index = index - h;
				}
				
				array[index] = temp;
			}
			h = (h-1)/3;
		}
	}
	
	public static void Display(int[] array, String str)
	{
		System.out.println(str);
		for(int i=0; i<array.length; i++)
			System.out.print(array[i] + "  ");
		System.out.println();
	}
}

 

 

输出结果为:

 

Befor sort: 
23  6  18  20  45  31  79  3  64  82  99  1  
After sort: 
1  3  6  18  20  23  31  45  64  79  82  99 

 

2
2
分享到:
评论
1 楼 汪兆铭 2009-05-04  
3叉树排序~

相关推荐

Global site tag (gtag.js) - Google Analytics