参考了几个网上例子,验证后发现,不是最后几个元素会产生环,要么就是排序后不是稳定的(相同key值的元素,会意外改变顺序)
最后自己写了个例子,用了2种方法写基于链表的插入排序,
#include <stdio.h>
#include <stdlib.h>
#define null 0
struct node;
struct node{
struct node *n;
void *d;
int k;
int val;
};
typedef struct node nod;
struct node* init(int size, int *val){
struct node *head = malloc(sizeof(struct node));
struct node *c = head;
head->k = 0;
for(int i = 0; i < size; i++){
struct node *n= malloc(sizeof(struct node));
n->k = val[i];
n->val = i;
c->n = n;
c = n;
}
c=head->n;
free(head);
return c;
}
void print_n(struct node *n){
while(n != null){
printf("%d(%d) -> ",n->k,n->val);
n = n->n;
}
printf("\n");
}
nod* insert_sort3(nod *h){
nod *pre;
nod *p,*cur,*n;
nod *dummy = malloc(sizeof(nod));
dummy->n = h;
p=dummy;
//pre=dummy;
cur=h;
//n=h;
while(cur != null){
n = cur->n;
pre = dummy;
while(pre != null && pre->n != null && pre->n->k <= cur->k && pre->n != cur){// stabilize
pre = pre->n;
}
if(pre->n == cur){
p = p->n;
}else{
cur->n = pre->n;
pre->n = cur;
p->n = n;
}
cur = n;
}
h = dummy->n;
free(dummy);
return h;
}
void main(){
int val[] = {3,6,2,1,5,4,2,4};
int len = sizeof(val)/sizeof(val[0]);
nod *n = init(len,val);
nod *n2 = init(len,val);
printf("original data : \n");
print_n(n);
printf("sorted data : \n");
nod *sn2 = insert_sort3(n2);
print_n(sn2);
}
输出:
root@ubuntu:~/cdir# gcc insert_sort_linkedlist.c -o insert_sort_linkedlist.bin -g
root@ubuntu:~/cdir# ./insert_sort_linkedlist.bin
original data :
3(0) -> 6(1) -> 2(2) -> 1(3) -> 5(4) -> 4(5) -> 2(6) -> 4(7) ->
sorted data :
1(3) -> 2(2) -> 2(6) -> 3(0) -> 4(5) -> 4(7) -> 5(4) -> 6(1) ->
通过括号内给的 val 值,可以看到 ,相同key的 2 和 4,排序后,相对位置没有发生改变,保证了稳定性
睡觉
来源:oschina
链接:https://my.oschina.net/u/4343037/blog/3353811