Thumbnail: jekyll

插入排序——直接插入排序

on under jekyll
1 minute read

算法描述:

  1. 第i趟排序,其前i-1个元素构成的子序列是排序的,将元素第i个插入到排序好的子序列中,使插入后的子序列仍然是排序的。
  2. 重复步骤1,n个元素排序需要n-1趟扫描

稳定性:稳定。

时间复杂度:

最好的情况(已排序):比较n-1次,移动0次,时间复杂度为O(n)

最差的情况(逆序):比较(n+2)(n-1)次,移动(n+4)(n-1)/2次,时间复杂度为O(n^2)

随机的情况:O(n^2)

空间复杂度:O(1)

Java实现:


//排序算法:直接插入排序
public class M001 {
	public static void main(String[] args) {
		int[] number = { 21, 32, 2, 4, 65, 90, 54 };
		int[] result = insertSort(number);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i] + " ");
		}

	}

	private static int[] insertSort(int[] number) {

		for (int i = 1; i < number.length; i++) {// n-1趟扫描
			int temp = number[i], j; // 每趟将第i个元素插入到前边的排序序列中
			for (j = i - 1; j >= 0 && number[j] > temp; j--) {// 将前边的较大的往后移
				number[j + 1] = number[j];
			}
			number[j + 1] = temp;// temp值到达插入位置
		}
		return number;
	}
}


学习笔记, 数据结构, Java, 排序
comments powered by Disqus