插入排序,在算法导论里面的介绍对数组 A[ ] = { 5, 2, 4,6,1,3 } 进行插入排序,排序的过程如下:
排序过程
a-->b-->c-->d-->e-->f
非降序插入排序
伪代码
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence 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语言代码
int insert_sort(int A[], int size)
{
int i, j, key;
if (NULL == A || size <=1 ){
printf("File:[%s] Line:[%s] illegal array\n", __FILE__, __LINE__);
return -1;
}
for(j=1; j<size; ++j){
key = A[j];
// inser A[j] to the sorted sequence A[1...j-1]
i = j - 1;
while (i >= 0 && A[i] > key){
A[i+1] = A[i];
i = i - 1;
}
A[i+1] = key;
}
return 0;
}
非升序插入排序伪代码
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence 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
插入排序改进
二分插入排序
伪代码
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence A[1...j-1]
i = j - 1
if A[i] > key
k = binary_search()
for i to k
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
C语言代码
#define INT_AVERAGE(A,B) ((A)&(B))+(((A)^(B))>>1)
int insert_sort(int A[], int size)
{
int i, j, key;
int pos, k;
if (NULL == A || size <=1 ){
printf("File:[%s] Line:[%s] illegal array\n", __FILE__, __LINE__);
return -1;
}
for(j=1; j<size; ++j){
key = A[j];
i = j - 1;
if (A[i] > key){
pos = interative_binary_search(A, key, 0, i);
for (; i>=pos; --i)
A[i+1] = A[i];
}
A[i+1] = key;
}
return 0;
}
int interative_binary_search(int A[], int v, int low, int high)
{
int mid;
while (low < high){
mid = INT_AVERAGE(low, high);
if (v > A[mid])
low = mid + 1;
else
high = mid - 1;
}
return low;
}
参考:
[1] 算法导论