Algorithm learning, algorithm Learning Website
Merge Sorting
I have already talked about Merge Sorting before, and gave the Merge Sorting method in the case of array series, and the time complexity of sorting is O (NlogN ). the link is as follows:
Merge Sorting, fast sorting, and Bubble Sorting
However, this Merge Sorting has a disadvantage: the extra space of O (n) is required.
So under what circumstances will this disadvantage be solved? That is, when the series are stored as linked lists! No additional O (n) level space is required.
So why do we need to sort by merging? Isn't there a fast sort, heap? They are all sorted quickly. In fact, it is not suitable for linked lists! In the fast sorting, the benchmark is of the O (1) level, but only the head node can be obtained in the linked list. The benchmark must be of the O (n) level. Then the complexity increases to (nNLogn) level.
Code Implementation
Therefore, in the case of a linked list, Merge Sorting is required. The complexity is NlogN, and no additional space is required.
//// 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 (m Id! = 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;} 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 = new ListNode (1); head-> next = new ListNode (3); sl. sortList (head); return 0 ;}