和选择排序一样,当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。当索引到达数组的右端时,数组排序就完成了。
和选择排序不同的是,插入排序所需要的时间取决于输入中元素的初始顺序。对一个很大且其中的很多元素已经有序的数组会比无序数组或逆序数组排序要快的多。
JavaScript
function insertSort(ary) {
var i, j, len = ary.length;
var temp;
for(i=1; i<len; i++) {
temp = ary[i];
for(j=i; j>0 && temp<ary[j-1]; j--) {
ary[j] = ary[j-1];
}
ary[j] = temp;
}
return ary;
}
var ary = [5,4,3,2,1];
console.log(insertSort(ary));
Java
public class Test {
public static void insertSort(int[] ary){
int i, j, temp;
int len = ary.length;
for(i=1; i<len; i++) {
temp = ary[i];
for(j=i; j>0 && temp<ary[j-1]; j--) {
ary[j] = ary[j-1];
}
ary[j] = temp;
}
}
public static void main(String[] args) {
int[] ary = {5,4,3,2,1};
Test.insertSort(ary);
for(int it : ary) {
System.out.println(it);
}
}
}
C
#include <stdio.h>
void insertSort(int ary[], int len) {
int i, j, temp;
for(i=1; i<len; i++) {
temp = ary[i];
for(j=i; j>0 && temp<ary[j-1]; j--) {
ary[j] = ary[j-1];
}
ary[j] = temp;
}
}
main() {
int i;
int ary[] = {5,4,3,2,1};
insertSort(ary, 5);
for(i=0; i<5; i++) {
printf("%d", ary[i]);
}
}