简单插入排序
伪代码
InsertSort (input ele[],input length)
for i <- 2 to length step 1
key <- ele[i]
for j <- i - 1 to 1 where (key < ele[i]) step -1
ele[j+1] <- ele[j]
end
ele[j+1] <- key
end
下面这一段是摘自算法导论第三版P18页的伪代码:
INSERT-SORT(A)
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted squence A[1...j - 1]
i = j - 1
while i > 0 and A[i] > key
A[i+1] = A[i]
i = i - 1
A[i + 1] = key
C++/C
void insertsort(int a[],int length)
{
int i,j;
for (i = 1;i < length;i++)
{
int key = a[i];
for (j = i - 1;j >= 0 && key < a[j]; j-- )
{
a[j+1] = a[j];
}
a[j+1] = key;
}
}
python
def InsertSort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while (j >= 0 and array[j] > key):
array[j + 1] = array[j]
j = j - 1
array[j+1] = key
Java
public class insertsort {
public static void main(String args[])
{
int [] array = {5, 7, 1, 9, 3, 4, 2, 8, 6, 0};
for (int k : array)
System.out.print(k + " ");
int i, j;
System.out.println();
for (i = 1; i < array.length; i++)
{
int key = array[i];
for (j = i-1; j >= 0 && key < array[j]; j--)
array[j+1] = array[j];
array[j+1] = key;
}
for (int k : array)
System.out.print(k + " ");
}
}
其实算法思想很简单,就是将第i个元素插入到前面有序的i-1个元素之中。
由于数组的局限性,必须通过循环,向后覆盖的方式来进行插入操作。
python重构
如果用python的切片和list下的index操作,所写如下:
def insort_sort (list):
for i in list[1:]:
for j in list[0:list.index(i)]:
if i < j:
list[list.index(j)+1:list.index(i)+1] = list[list.index(j):list.index(i)]
list[list.index(j)] = i
break
return list
list = [1, 4, 0, 3, 5, 2, 9, 8, 6, 7]
print insort_sort(list)