排序算法之直接插入排序

概念

从第2个元素开始,将每一个元素插入到已经排好序的序列中,得到一个新的排好序的序列

 

Java版实现

	public static void insert(Integer[] array) {
		Integer s;
		int j;
		for (int i = 1; i < array.length; i++) {
			if (array[i] < array[i-1]) {
				s = array[i];
				for (j = i-1; j >= 0 && array[j] > s; j--)
					array[j+1] = array[j]; // move the element backward
				array[j+1] = s; // put the ith element in the right place
			} // end if the element i-1 larger than element i
		} // end for loop and compare length-1 times
	}

 

时间复杂度分析

最差情况,初始为倒序序列,需要比较的次数为(n-1)(n+2)/2次,需要移动(n+4)(n-1)/2次,时间复杂度为O(n2)

最好情况,初始为已排序序列,需要比较的次数为n-1次,需要移动0次,时间复杂度为O(n)

与冒泡和简单选择排序比较,个人觉得并没有体现优势

 

空间复杂度分析

需要的辅助空间为O(1)

posted @ 2013-12-24 01:03  sxplus  阅读(189)  评论(0编辑  收藏  举报