【基础算法】排序-简单排序之三(插入排序)

一. 一般插入排序

想象一下打扑克,每次都把摸上来的牌放到正确的位置,插入排序也一样,从第二个数开始依次和第一个数比较,直到放到正确的位置为止,时间复杂度为O(N^2/4), 证明如下:



代码如下

	// compare
	public static boolean more(int v, int w) {
		return v > w;
	}

	// exchange
	public static void exchange(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	// insertionSort Algorithm
	public static void insertionSort(int[] array) {
		for (int i = 1; i < array.length; i++) { // i++
			for (int j = i; j > 0; j--) {
				if (more(array[j-1], array[j]))
					exchange(array, j-1, j );
				else
					break;
			}
		}
	}

二. 希尔插入排序

我们发现,插入排序在初始序列排好序的情况下时间复杂度为O(N),所以有没有一种算法可以改进初始序列使其无限接近与排好序的序列

希尔排序就是这个目的,这种排序通过分割的方法让初始序列无限优化,直到最后一次进行插入排序的时候,序列无限接近于排好序的状况。

代码如下

	// compare
	public static boolean more(int v, int w) {
		return v > w;
	}

	// exchange
	public static void exchange(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	// insertionSort Algorithm
	public static void shellSort(int[] array) {
		int increment = 1;
		while (increment < array.length / 3)
			increment = 3 * increment + 1; // 3X+1 increment sequence

		while (increment >= 1) {
			for (int i = 1; i < array.length; i++) { // i++
				for (int j = i; j >= increment; j = j - increment) {
					if (more(array[j-increment], array[j]))
						exchange(array, j, j - increment);
					else
						break;
				}
			}
			increment = increment / 3;
		}
	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值