作者:Brian 来源:BlogJava 酷勤网收集 2008-06-12
一.插入排序算法的思路
假定这个数组的序是排好的,然后从头往后,如果有数比当前外层元素的值大,则将这个数的位置往后挪,直到当前外层元素的值大于或者等于它前面的位置为止。
二.插入排序算法实例
用五个名字(Monroe,Chin,Flores,Stein和Dare)的列表的插入排序算法为例:
Monroe 从Monroe开始
处理名字Chin Chine Monroe 将Chin插入到位置0;Monroe移动至位置1
处理名字Flores Chine Flores Monroe 将Flores插入到位置1;Monroe移动至位置2
处理名字Stein Chine Flores Monroe Stein Stein位置正确
处理名字Dare Chine Dare Flores Monroe Stein 将Dare插入在位置1;列表尾部向右移动
三.插入排序算法的实现(Java语言)

public class InsertSort
{
//sort an array of elements using insertion sort
public static <T extends Comparable<? super T>> void sort(T[] arr)
{
int i, j, n = arr.length;
T target;

/** *//**
* place element at index i into the sublist
* from index 0 to i-1 where 1<= i,
* so it is in the correct positon
*/
for (i = 1; i < n; i++)
{
//index j scans down list from index i looking for
//correct position to locate target; assigns it to
//arr at index j
j = i;
target = arr[i];
//locate insertion point by scanning downward as long
//as target < arr[j] and we have not encountered the
//beginning of the array
while (j > 0 && target.compareTo(arr[j - 1]) < 0)
{
//shift elements up list to make room for insertion
arr[j] = arr[j - 1];
j--;
}
//the location is found;insert target
arr[j] = target;
}
}
}
四.插入排序算法的效率
假定n是数组的长度,那么插入排序需要n-1遍。对于通用的遍i来说,插入操作从arr[0]到arr[i-1]的子列表中,并且需要平均i/2次比较。比较的平均总数为:
T(n) = 1/2 + 2/2 + 3/2 + ...... + (n-2)/2 + (n-1)/2 = n(n-1)/4
根据T(n)的主项,插入排序算法的平均运行时间为O(n2)。最好情况为O(n),最坏情况为O(n2)。

