Merge sort
Merge sort I've talked about it before, and I've given you a merge sort method in the case of array numbers, and the sorting time is O (nlogn). If you want to see it, the link is as follows:
Merge sort, quick row, bubble sort
But this merge sort has one drawback: an extra space of O (n) is required.
So, under what circumstances will this shortcoming be solved? Is that the sequence is stored in the form of a chain list! There is no need to apply for an O (n) level of space.
So why do we have to sort by merging? No, there's a quick platoon. Are very fast sort of. In fact, in the list is not suitable! Because the search benchmark is O (1) at the time of the queue, only the head node can be found in the list, and an O (n) level is required to get the benchmark. Then the complexity rises to the (nnlogn) level.
Code implementation
Therefore, in the case of the linked list needs to use the merge sort, the complexity nlogn, and does not need to request the extra space.
main.cpp//mergelist////Created by Alps on 14/12/6.//Copyright (c) 2014 Chen. All rights reserved.//#include <iostream>using namespace std;struct listnode{int val; Listnode* Next; ListNode (int x): Val (x), Next (NULL) {}};class solution{public:listnode *sortlist (listnode* head) {if (head = = NULL || Head->next = = NULL) {return head; } listnode* mid = Getmid (head); listnode* right = NULL; if (Mid! = NULL) {right = mid->next; Mid->next = NULL; } head = Sortlist (head); right = Sortlist (right); Head = Mergelist (head, right); return head; } listnode* Getmid (listnode* node) {if (node = = NULL | | node->next = = NULL) {return node; } listnode* l1 = node; listnode* L2 = node->next; while (L2 && l2->next) {L1 = l1->next; L2 = l2->next->next; } return L1; } listnode* Mergelist (listnode* left, listnode* right) {if (left = = NULL) {return right; } if (right = = NULL) {return left; } listnode* temp = NULL; if (left->val >= right->val) {temp = right->next; Right->next = left; left = right; right = temp; } Left->next = Mergelist (Left->next, right); return left; }};int Main (int argc, const char * argv[]) {solution SL; ListNode *head = new ListNode (4); Head->next = new ListNode (2); Head->next->next = new ListNode (1); Head->next->next->next = new ListNode (3); Sl.sortlist (head); return 0;}
Algorithm Learning-List merge sort _o (1) Space _o (NLOGN) Time _c++