经典排序之插入排序

一、插入排序

1.基本思想:通过对未排序的数据逐个插入至合适的位置而完成排序工作。

2.代码实现

public class InsertionSort {
	
	static final int SIZE = 10;
	
	static void insertionSort(int[] a) {
		int i,j,t,h;
		for(i = 1; i < a.length; i++) {
			t = a[i];
			j = i - 1;
			while(j >= 0 && t < a[j]) {
				a[j+1] = a[j];
				j--;
			}
			a[j+1] = t;
			System.out.print("第"+i+"步排序结果:");
			for(h = 0; h < a.length; h++) {
				System.out.print(" "+a[h]);
			}
			System.out.print("\n");
		}
	}
	
	/*在上述代码中,首先将需要插入的元素保存在变量t中。变量j表示需要插入的位置,一般就是插入的数组的序号。
	 * 设置变量j的值为i-1,表示准备将当前位置(序号为i)的数插入序号为i-1的位置,接着,算法程序通过while
	 * 循环来进行判断,如果序号为 j元素的数据大于变量 t,则将序号为j的元素向后移,同时j减一,以判断前一个数据
	 * 是否还需向后移。通过该while循环找到一个元素的值别t小,该元素是j,然后将序号为j的下一个元素进行数据插入操作*/

	public static void main(String[] args) {
		int[] shuzu = new int[SIZE];
		int i;
		
		for(i = 0; i < SIZE; i++) {
			shuzu[i] = (int)(100+Math.random()*(100+1));
		}
		
		System.out.print("排序前的数组为:\n");
		for(i=0;i<SIZE;i++) {
			System.out.print(shuzu[i]+" ");
		}
		System.out.print("\n");
		insertionSort(shuzu);
		
		System.out.print("排序后的数组为:\n");
		for(i=0;i<SIZE;i++) {
			System.out.print(shuzu[i]+" ");
		}
		System.out.print("\n");
	}

}

 

二、Shell排序

1.基本思想:基于插入排序,又称为希尔排序或缩小增量排序,其排序流程如下:

(1)将有n个元素的数组分为n/2个数字序列,第1个数据和第n/2+1个数据为一对,........;

(2)一次循环使每一对序列排好序列;

(3)然后,再变为n/4个序列,再次排序;

(4)不断重复上述过程,随着序列减少为最后一个,也就完成了整个序列;

当是大量数据且部分有序时,shell排序算法效率较高。

二、代码实现

public class ShellSort {
	static final int SIZE = 10;
	static void shellSort(int[] a) {
		int i,j,h;
		int r,temp;
		int x = 0;
		
		for(r = a.length/2;r>=1;r/=2) {
			for(i = r;i<a.length;i++) {
				temp = a[i];
				j = i-r;
				while(j >= 0 && temp < a[j]) {
					a[j+r] = a[j];
					j-=r;
				}
				a[j+r] = temp;
			}
			x++;
			System.out.print("第"+x+"步排序结果:");
			for(h=0;h<a.length;h++) {
				System.out.print(" "+a[h]);
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		int[] shuzu = new int[SIZE];
		int i;
		
		for(i=0;i<SIZE;i++) {
			shuzu[i] = (int)(100+Math.random()*(100+1));
		}
		
		System.out.println("排序前的数组:");
		for(i = 0; i < SIZE; i++) {
			System.out.print(shuzu[i]+" ");
		}
		System.out.println();
		shellSort(shuzu);
		
		System.out.println("排序后的数组:");
		for(i = 0; i < SIZE; i++) {
			System.out.print(shuzu[i]+" ");
		}
		System.out.println();
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值