java排序-希爾排序

import java.util.Random;

public class Sort {
	public static int [] shellSort(int[] R)
	{
		int gap = R.length/2;
		int temp;
		while(gap>0)
		{
			for(int i=gap;i<R.length;i++)
			{
				temp = R[i];//從I開始放入臨時變量
				int j = i-gap;//根據步長確定要交換的對象
				while(j>=0&&temp<R[j])//條件:角標大於零並且後面的值小於前面的值
				{
					R[j+gap] = R[j];//相比較的兩個值互換位置
					j = j-gap;//角標互換位置
				}
				R[j+gap] = temp;//原本前面的值後移
			}
			gap = gap/2;//步長除以2
		}
		return R;
	}
	public static void display(int[] R)
	{
		System.out.println();
		for(int i=0;i<R.length;i++)
		{
			System.out.print(R[i]+" ");
		}
	}
	public static void main(String[] args)
	{
		final int M = 10;
		int[] R = new int[M];
		for(int i=0;i<M;i++)
		{
			R[i] = new Random().nextInt(100);
		}
		display(R);
		R = shellSort(R);
		display(R);
	}
}

留着備查
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章