1. 算法思想
见:插入排序
2. 程序
数组实现
//从大到小排序
void InsertSort(int a[], int N)
{
int j, p, tem;
for (p = 1; p < N; p++) {
tem = a[p];
for (j = p; j > 0 && a[j-1] < tem; j--)
a[j] = a[j-1];
a[j] = tem;
}
}
时间复杂度为 O ( N 2 ) O(N^2) O(N2)。
单链表实现
用单链表实现每次比较都要从首节点开始比较
//从大到小排序
struct node;
typedef struct node *ptrtonode;
typedef ptrtonode list;
typedef ptrtonode position;
struct node {
int data;
ptrtonode next;
};
//判断链表是否为空链表
int IsEmpty(list L)
{
return L->next == NULL;
}
//将q指向的节点插入到p指向的节点后,bq指向原来q指向的节点的前一个节点
//移动q指向的节点时要先将它前面的节点与它后面的节点连在一起
void InsertAfter(position p,position q,position bq)
{
bq->next = q->next;
q->next = p->next;
p->next = q;
}
/*ptemp初始指向首节点后一个节点,从该节点开始插入,该节点前面的节点都已经排序好,每次要插入需要从首节点开始比较,如果待插入节点比首节点小,则继续向后比较,直到遇到比待插入节点大的节点,这种情况就将插入到该比较节点前面,或者一直扫描完成迟到遇到待插入节点,则直接将待插入节点插入已排序好链表末尾。
*/
void InsertSort(list L)
{
if (IsEmpty(L)) {
fprintf(stderr,"Empty linked list\n");
exit(EXIT_FAILURE);
}
position p, pbefore;
position ptemp = L->next->next, pbtemp = L->next;
while (ptemp != NULL) {
p = L->next;
pbefore = L;
while (p != ptemp && ptemp->data < p->data) {
pbefore = p;
p = p->next;
}
//已排序好的节点扫描完都比待插入节点大,则不需要改变位置
if (p == ptemp) {
pbtemp = ptemp;
ptemp = ptemp->next;
}
else {
InsertAfter(pbefore,ptemp, pbtemp);
ptemp = pbtemp->next;
}
}
}
双链表实现
双链表实现和数组一样,每次比较从后往前扫描
struct node;
typedef struct node *ptrtonode;
typedef ptrtonode list;
typedef ptrtonode position;
struct node {
ptrtonode prior;
int data;
ptrtonode next;
};
int IsEmpty(list L)
{
return L->next == NULL;
}
position InsertAfter(position p, position q)
{
position bq = q->prior;
if (p != bq) {
bq->next = q->next;
q->next->prior = bq;
q->next = p->next;
p->next->prior = q;
p->next = q;
q->prior = p;
return bq->next;
}
return q->next;
}
void InsertSort(list L)
{
if (IsEmpty(L)) {
fprintf(stderr,"Empty linked list\n");
exit(EXIT_FAILURE);
}
position ptemp = L->next->next, p;
while (ptemp != NULL) {
p = ptemp->prior;
while (p != L && ptemp->data > p->data)
p = p->prior;
ptemp = InsertAfter(p,temp);
}
}