Java implements quick sort and merge sort of single-linked list

Source: Internet
Author: User

This paper describes the solution of Leetcode 148 sort-list.

The topics are described as follows:
Sort a linked list in O (n log n) time using constant space complexity.

The topic asks us to sort the single-linked list in O (n log n) time complexity, and we know that the average time complexity of O (n log n) is sorted by quick sort, merge sort, and heap sort. Instead of using an array to implement a two-fork heap, of course, you can use a binary tree, but it's too cumbersome to spend extra space to build a binary tree, so you don't use heap sorting.

So this paper uses the quick sort and the merge sort to sort the single linked list.

Quick Sort

In the general implementation of the fast ordering, we use the end-to-end pointer to the elements of the segmentation, the following is another way of the fast row to slice the elements.

We only need two pointers P1 and P2, both pointers moving in the next direction, the movement of the process to keep P1 before the key is less than the selected Key,p1 and P2 between the key is greater than the selected key, then when the P2 to the end of the Exchange P1 and the key value to complete a slice.

This is illustrated below:

The code is as follows:

 PublicListNodesortlist(ListNode head) {//Use quick sort   QuickSort(Head,NULL);returnHead;} Public Static void QuickSort(ListNode head, ListNode end) {if(head! = end) {ListNode node =partion(head, end);QuickSort(Head, node);QuickSort(node.Next, end); }} Public StaticListNodepartion(ListNode head, ListNode end) {ListNode P1 = head, p2 = head.Next;//Go to the end before stopping     while(P2! = end) {//greater than the key value, P1 step forward, exchanging values for P1 and P2        if(P2.Val< head.Val) {P1 = P1.Next;inttemp = P1.Val; P1.Val= P2.Val; P2.Val= temp; } P2 = p2.Next; }//when ordered, P1 and key values are not exchanged    if(P1! = head) {inttemp = P1.Val; P1.Val= head.Val; Head.Val= temp; }returnP1;}
Merge sort

The merge sort should be ranked as the best choice for the list of links, ensuring that the best and worst-case complexity are NLOGN, and that the spatial complexity in which it is widely criticized in array sorting is also reduced from O (n) to O (1) in the list ordering.

The general steps for merge sorting are:

    1. The array to be sorted (linked list) takes the midpoint and divides it into split;
    2. Recursive to the left half of the merge sort;
    3. Recursively merges the right half of the sequence;
    4. Combine the two halves (merge) to get the results.

First with the fast and slow pointer (quick and slow pointer idea, the rapid hands walk two steps at a time, the fast pointer at the end of the list, the slow pointer exactly in the link table midpoint) method to find the middle node of the list, and then recursive to two sub-linked list, the two ordered sub-linked list into an orderly list.

The code is as follows:

 PublicListNodesortlist(ListNode head) {//Using merge sort    if(Head = =NULL|| Head.Next==NULL) {returnHead }//Get the middle node.ListNode mid =Getmid(head); ListNode right = Mid.Next; Mid.Next=NULL;//Merger    return MergeSort(sortlist(head),sortlist(right));}/*** Gets the middle node of the list, even when the middle of the first * * @param head* @return */PrivateListNodeGetmid(ListNode head) {if(Head = =NULL|| Head.Next==NULL) {returnHead }///Speed indicatorListNode slow = head, quick = head;//Fast 2 steps, one step slower     while(Quick.)Next!=NULL&& Quick.Next.Next!=NULL) {slow = slow.Next; Quick = quick.Next.Next; }returnSlow;}/** ** Merge two ordered linked lists * * @param head1 * @param head2* @return */PrivateListNodeMergeSort(ListNode head1, ListNode head2) {ListNode P1 = head1, p2 = head2, head;//Get to the point of the head node    if(Head1.Val< head2.Val) {head = Head1; P1 = P1.Next; }Else{head = head2; P2 = p2.Next; } ListNode p = head;//Compare values in a linked list     while(P1! =NULL&& P2! =NULL) {if(P1.Val<= P2.Val) {p.Next= P1; P1 = P1.Next; p = P.Next; }Else{p.Next= P2; P2 = p2.Next; p = P.Next; }    }//Second linked list empty    if(P1! =NULL) {p.Next= P1; }//The first linked list is empty    if(P2! =NULL) {p.Next= P2; }returnHead;}

The complete code is placed in:
Https://github.com/morethink/algorithm/blob/master/src/algorithm/leetcode/SortList.java

reference Documentation :

    1. List sort (bubble, select, insert, fast, merge, Hill, heap sort)

Java implements quick sort and merge sort of single-linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.