码迷,mamicode.com
首页 > 其他好文 > 详细

Insertion Sort List

时间:2016-04-20 07:07:25      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

刚开始想的复杂很多,后来重新思考了一遍,发现是我想太复杂了。

这个是重改后的第一版,发现效率还能继续提升:

if(head==NULL || head->next==NULL) return head;
ListNode* nh=head;
head = head->next;
nh->next = NULL;
while(head!=NULL) {
if(head->val < nh->val) {
ListNode *a = head->next;
head->next = nh;
nh = head;
head = a;
}
else {
if(nh->next == NULL) {
nh->next = head;
head = head->next;
nh->next->next = NULL;
continue;
}
ListNode *p = nh;
while(p->next && head->val > p->next->val) {
p = p->next;
}
if(p->next) {
ListNode *a = head->next;
head->next = p->next;
p->next = head;
head = a;
}
else {
p->next = head;
head = head->next;
p->next->next = NULL;
}
}
}
return nh;

 

当插入结点head一直大于当前结点p的时候,p可以不归位,这样节省了很多效率,改进后代码如下:

ListNode* insertionSortList(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode *nh=head, *p=nh;
head = head->next;
nh->next = NULL;
while(head!=NULL) {
if(head->val < nh->val) {
ListNode *a = head->next;
head->next = nh;
nh = head;
head = a;
}
else {
if(p->val > head->val) {
p = nh;
}
while(p->next && head->val > p->next->val) {
p = p->next;
}
if(p->next) {
ListNode *a = head->next;
head->next = p->next;
p->next = head;
head = a;
}
else {
p->next = head;
head = head->next;
p->next->next = NULL;
}
}
}
return nh;
}

 

效率对比:改进前测试速度为80ms,改进后测试速度为24ms,节省了70%的时间!

Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/xdlyy/p/5410979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!