插入排序的主要思想每次从待排序的数组中取一个值,按其值的大小插入到已经排好序的数组中的适当位置上,直到全部插入完为止。
插入排序的时间复杂度最好为O(n), 最坏为O(n2), 平均时间复杂度为O(n2)。
插入排序是一种稳定的排序算法。
以数组89 37 23 4 54 17 49 为例,排序的过过程如下:
原-->89 37 23 4 54 17 49
1-->37 89 23 4 54 17 49
2-->23 37 89 4 54 17 49
3-->4 23 37 89 54 17 49
4-->4 23 37 54 89 17 49
5-->4 17 23 37 54 89 49
6-->4 17 23 37 49 54 89
直接上代码:
C:
//插入排序
void insert_sort(int array[], int len) {
for(int i=1; i<len; i++) {
int temp = array[i];
int j=i-1;
while (j>=0 && array[j] > temp) {
array[j+1] = array[j];
j--;
}
if(j != i-1) {
array[j+1] = temp;
}
}
}
function insertSort(array $array) {
$len = count($array);
for($i=1; $i<$len; $i++) {
$temp = $array[$i];
$j = $i-1;
while($j>=0 && $array[$j] > $temp) {
$array[$j+1] = $array[$j];
$j--;
}
if($j != $i-1) {
$array[$j+1] = $temp;
}
}
}
Python:
def insertSort(array=None):
if array is None:
return
length = len(array)
for i in range(1, length):
temp = array[i]
j = i-1
while j>=0 and array[j] > temp:
array[j+1] = array[j]
j -= 1
if j != i-1:
array[j+1] = temp