希尔排序---java


插入排序

import java.util.*;

public class InsertSort
{
	public static int[] sort(int[] x)
	{
		int N = x.length;
		
		int[] a = new int[N];
		
		for (int i = 0; i < N; i++)
			a[i] = x[i];
		
		for (int i = 1; i < N; i++)
			for (int j = i; j >= 1 && less(a, j, j-1); j--)
				swap(a, j, j-1);
		
		return a;
	}
	
	private static boolean less(int[] x, int i, int j)
	{
		return x[i] < x[j];
	}
	
	private static void swap(int[] x, int i, int j)
	{
		int t = x[i];
		x[i] = x[j];
		x[j] = t;
	}
	
	public static void main(String[] args)
	{
		Random random = new Random();
		
		int[] a = new int[20];
		for (int i = 0; i < 20; i++)
			a[i] = random.nextInt(100);
		
		StdOut.println(Arrays.toString(a));
		
		int[] r = sort(a);
		
		System.out.println(Arrays.toString(r));
	}
}

/*
[42, 63, 92, 76, 10, 99, 75, 78, 0, 8, 84, 52, 54, 16, 97, 30, 39, 76, 50, 9]
[0, 8, 9, 10, 16, 30, 39, 42, 50, 52, 54, 63, 75, 76, 76, 78, 84, 92, 97, 99]
*/


希尔排序

import java.util.*;

public class ShellSort
{
	public static int[] sort(int[] x)
	{
		int N = x.length;
		
		int[] a = new int[N];
		
		for (int i = 0; i < N; i++)
			a[i] = x[i];
		
		int step = 1;
		
		while (step < N/3)
		{
			step = step * 3 + 1; // 1,4,13,40,121...
		}
		
		while (step >= 1)
		{
			for (int i = step; i < N; i++)
			{
				for (int j = i; j >= step && less(a, j, j - step); j -= step)
					swap(a, j, j-step);
			}				
			
			step /= 3;
		}
		
		return a;
	}
	
	private static boolean less(int[] x, int i, int j)
	{
		return x[i] < x[j];
	}
	
	private static void swap(int[] x, int i, int j)
	{
		int t = x[i];
		x[i] = x[j];
		x[j] = t;
	}
	
	public static void main(String[] args)
	{
		Random random = new Random();
		
		int[] a = new int[20];
		for (int i = 0; i < 20; i++)
			a[i] = random.nextInt(100);
		
		StdOut.println(Arrays.toString(a));
		
		int[] r = sort(a);
		
		System.out.println(Arrays.toString(r));
	}
}

/*
[79, 43, 40, 5, 9, 80, 4, 77, 97, 2, 14, 97, 55, 77, 20, 90, 41, 64, 82, 94]
[2, 4, 5, 9, 14, 20, 40, 41, 43, 55, 64, 77, 77, 79, 80, 82, 90, 94, 97, 97]
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值