排序算法之直接插入排序

概念java

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

 

Java版实现blog

	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)element

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

与冒泡和简单选择排序比较,我的以为并无体现优点class

 

空间复杂度分析im

须要的辅助空间为O(1)static

相关文章
相关标签/搜索