O(nlogn)时间复杂度 链表排序
2011-09-08 23:35
330 查看
可以使用归并排序
int counter = 0;// statistic struct list_node { int val; struct list_node* next; list_node(int t, struct list_node* pn = 0) { val = t; next = pn; } }; typedef list_node* list; void insert_list(list& h, int t) { if (0 == h) { h = new list_node(t); return; } list pn = new list_node(t, h); h = pn; } // find the middle node of the list list find_mid(list h) { list pn = h; if (0 == pn->next || 0 == pn) return pn; while(h != 0 && h->next != 0)// && h->next->next != 0) // it is needless { pn = pn->next; h = h->next->next; } return pn; } list merge_list(list h1, list h2) { list hret = (0 != h1) ? h1:h2;// head of the returned list if (0 == hret) return hret; hret = (h1->val < h2->val) ? h1:h2; if (hret == h1) h1 = h1->next; else h2 = h2->next; list ret = hret; // the last node of the returned list while( (0 != h1) && (0 != h2) ) { counter ++;// no usage, just for statistic if (h1->val < h2->val) { ret->next = h1; ret = h1;// reassign ret h1 = h1->next; } else { ret->next = h2; ret = h2;// reassign ret h2 = h2->next; } } // attach the remained nodes to the ret list if (0 != h1) ret->next = h1; else if(0 != h2) ret->next = h2; else ret->next = 0; // 0 is the end of the returned list return hret; } list merge_sort_list(list h) { if (0==h ||0==h->next) return h; list mid1 = find_mid(h); if (0 == mid1) return 0; list mid = mid1->next; mid1->next = 0;// break up the list h into h and mid list h1 = merge_sort_list(h); list h2 = merge_sort_list(mid); counter++;// no usage, just for statistic return merge_list(h1, h2); } int main(int argc, char* argv[]) { list h = 0;// necessary to initialize, else h1 equal to 0xcccccccc for (int i=0 ;i< 4096; ++i) insert_list(h, rand()%100000); list ret = merge_sort_list(h); cout<<counter<<endl;// show how many operations while(0 != ret) { cout<<ret->val<<endl; ret = ret->next; } return 0; }
相关文章推荐
- C/C++ 数组,链表排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之归并排序
- 对链表排序 要求时间 复杂度为 O(nlogn) 空间复杂度为常量
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- 快速排序的时间复杂度nlogn是如何推导的??
- 在O(n log n)时间内使用常数空间复杂度对链表进行排序
- C/C++ 数组排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之快速排序
- 链表的排序 时间复杂度O(nlogn)
- 对链表排序,时间开销O(nlogn), 空间开销O(1)
- 每天一道LeetCode-----链表排序,要求复杂度在O(nlogn)
- 快速排序的时间复杂度nlogn是如何推导的??
- C++实现几种常用的时间复杂度为O(nlogn)的排序方法:归并排序、快速排序、堆排序、希尔排序
- 快速排序[平均时间复杂度O(NlogN)]
- 快速排序的时间复杂度nlogn是如何推导的??
- leetcode之时间复杂度为O(nlogn)的链表排序
- C/C++ 数组排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之堆排序
- 二、排序(时间复杂度 O(nlogn))
- C/C++ 数组排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之希尔排序
- 在O(1)时间复杂度删除链表节点
- lintcode——在O(1)时间复杂度删除链表节点
- LeetCode-Sort List,链表排序(插入和归并),时间复杂度O(n^2) and O(nlgn)