O(nlogn)时间复杂度 链表排序
来源:互联网 发布:shell脚本调用java类 编辑:程序博客网 时间:2024/05/20 16:32
可以使用归并排序
int counter = 0;// statisticstruct 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 listlist 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 listif (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 listwhile( (0 != h1) && (0 != h2) ){counter ++;// no usage, just for statisticif (h1->val < h2->val){ret->next = h1;ret = h1;// reassign reth1 = h1->next;}else{ret->next = h2;ret = h2;// reassign reth2 = h2->next;}}// attach the remained nodes to the ret listif (0 != h1)ret->next = h1;else if(0 != h2)ret->next = h2;else ret->next = 0; // 0 is the end of the returned listreturn 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 midlist h1 = merge_sort_list(h);list h2 = merge_sort_list(mid);counter++;// no usage, just for statisticreturn merge_list(h1, h2);}int main(int argc, char* argv[]){list h = 0;// necessary to initialize, else h1 equal to 0xccccccccfor (int i=0 ;i< 4096; ++i)insert_list(h, rand()%100000);list ret = merge_sort_list(h);cout<<counter<<endl;// show how many operationswhile(0 != ret){cout<<ret->val<<endl;ret = ret->next;} return 0;}
- O(nlogn)时间复杂度 链表排序
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- 对链表排序 要求时间 复杂度为 O(nlogn) 空间复杂度为常量
- 快速排序[平均时间复杂度O(NlogN)]
- leetcode之时间复杂度为O(nlogn)的链表排序
- 实现时间复杂度为O(nlogn)的链表排序算法
- LCS时间复杂度O(NlogN)
- 排序的最低时间复杂度为什么是O(nlogn)
- 归并排序平均时间复杂度O(NlogN)
- 二、排序(时间复杂度 O(nlogn))
- 单链表的归并排序:时间复杂度O(nlogn),空间复杂度O(1)
- 快速排序算法的时间复杂度为什么是O(NlogN),还有O(N^2)
- 每天一道LeetCode-----链表排序,要求复杂度在O(nlogn)
- 关于快速排序和插入排序最坏时间复杂度为O(nlogn)的算法
- 对链表排序,时间开销O(nlogn), 空间开销O(1)
- 基于比较的排序,时间复杂度下界是o(nlogn)的小证明
- 基于比较的排序,时间复杂度下界是o(nlogn)的小证明
- Java-时间复杂度为O(nlogn)的排序算法(快速排序, 归并排序, 堆排序, 希尔排序)
- Java的反射(reflect)机制的学习
- Android图像处理之Bitmap类
- How to add / install JSON support to PHP on CentOS in 10 Steps
- MongoDb学习笔记三 MongoDB and PyMongo
- QT QML 信号 处理 1
- O(nlogn)时间复杂度 链表排序
- 2011年8月
- 80后,我们就不买房!
- route print命令实例详解
- 开家公司?比你想的难多了
- 插入排序算法---java 实现
- 嵌入式Linux学习1——Linux相关命令介绍
- Java 命令行详解1
- C++Primer——迭代器iterator