插入排序

直接插入排序

 原理:将一个记录插入到已经排好的有序表中,从而得到一个新的、记录数增1的有序表。

对于给定的一组记录,初始时假定第一个记录自成一个有序序列,其余记录为无序序列。接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直到最后一个记录插到有序序列中为止。【简单来说,就是假定前面的序列已经排好序了,然后新的数字在这个序列中找到他自己的位置】

插入排序的性能要好于简单选择排序和冒泡排序。

稳定性:稳定的

时间复杂度:O(n^2)

代码如下

public class DirectInsertSort {
	public static void main(String[] args) {
		Integer[] array = { 23, -15, 14, 10, 22, 19, 65, 9 };
		int temp = 0;
		for (int i = 0; i < array.length; i++) {
			temp = array[i];
			int j;
			for (j = i - 1; j >= 0; j--) {
				if (array[j] > temp) {
					//大于temp的值都后移一位
					array[j + 1] = array[j];
				} else {
					break;
				}
			}
			if (j + 1 != i) {
				array[j + 1] = temp;
			}
		}
		ArrayUtil.out(array);
	}
}

  

public class ArrayUtil {
	public static <T> void out(T[] array) {
		for (T t : array) {
			System.out.print(t + " ");
		}

	}
}

  

原文地址:https://www.cnblogs.com/javabigdata/p/7269830.html