1. Merge sort
Merge sort is based on a strategy called "divide and conquer".
Sort List
Sort a linked list in O(n log n) time using constant space Complexity.
Method 1:merge sort, in the way of divide and conquer, first divides the list into the left and right parts, and then sorts the merged
sort list (divide and Conquer)
2. Quick Sort
Pseudo Code:
function quicksort (q) var list less, pivotlist, greater if length (q) ≤1 { return q } Else { Select a Pivot value pivot from Q for each x in Q except the pivot element if x < pivot then add X to less if X≥pi Vot then add x to greater add pivot to pivotlist return concatenate (quicksort (less), pivotlist, quicksort (greater )) }
LinkedList Quick Sort
public classSolution { publicListNode sortlist (listnode head) {if(head = =NULL|| Head.next = =NULL) { returnhead; } ListNode Mid= Findmedian (head);//O (n)//new three Dummmy node with a tail point to itListNode Leftdummy =NewListNode (0), Lefttail =leftdummy; ListNode Rightdummy=NewListNode (0), Righttail =rightdummy; ListNode Middledummy=NewListNode (0), Middletail =middledummy; //Sprate to three part while(head! =NULL) { if(head.val <Mid.val) {lefttail.next=head; Lefttail=head; } Else if(head.val >Mid.val) {righttail.next=head; Righttail=head; } Else{middletail.next=head; Middletail=head; } head=head.next; } //Make the tail to nullLefttail.next =NULL; Middletail.next=NULL; Righttail.next=NULL; //recurisive do the sortListNode left =sortlist (leftdummy.next); ListNode right=sortlist (rightdummy.next); //connect the three parts together returnconcat (left, middledummy.next, right); } Private Staticlistnode Findmedian (listnode head) {listnode Fast=head.next; ListNode Slow=head; while(fast! =NULL&& fast.next! =NULL) {slow=slow.next; Fast=fast.next.next; } returnslow; } Private Staticlistnode concat (listnode left, listnode mid, listnode right) {listnode dummy=NewListNode (0), Dummytail =dummy; Dummytail=Connect (dummytail, left); Dummytail=Connect (dummytail, mid); Dummytail=Connect (dummytail, right); returndummy.next; } Private StaticListNode Connect (listnode dummytail, listnode Current) { while(current! =NULL) {dummytail.next=current ; Dummytail=dummytail.next; current=current.next; } returndummytail; }}sortlist
Various sort notes---based on the Compare sort section