Algorithm--Quick sort (linked list)

Source: Internet
Author: User
Tags benchmark prev sorts strcmp

Quick Sort

http://m.blog.csdn.net/blog/u013071074/36867589

Quick Sort is a sort of algorithm developed by C. A. R. Hoare. The basic idea is the basic idea is that by a trip to the sorting of the records separated into two separate parts, some of the records of the keywords are smaller than the other part of the keyword, you can continue to order the two parts of the record to achieve the order of the whole sequence.

Quick sort use the divide-and-conquer method to divide a string (list) into two sub-serial (sub-lists).
The steps are:
1. Pick an element from the series called "Datum" (pivot),
2, reorder the series, all elements are smaller than the benchmark value placed in front of the benchmark, all elements are larger than the benchmark value of the base (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation.
3. Recursively (recursive) sorts sub-columns that are smaller than the base value elements and sub-numbers that are larger than the base value elements.
Worst time complexity: O (n^2)
Optimal time complexity: O (n log n)
Average time complexity: O (n log n)
Worst spatial complexity: different depending on how it's implemented

Algorithmic Understanding

This sorting algorithm, thought is divided and filtered:

Select an element as the split point, divide the list into two parts, the first part (the small portion of the score cut), and the second part (the part with the larger score cut).

So the whole list is divided into three parts: the dividing point, the first part and the second part.

Then, for the first and second parts, this filtering method (recursive execution) is executed separately until there is only one element in the list that is recursive.

Image point analogy, there is a basket of persimmon, choose a medium-sized persimmon, as a standard, this pile of persimmon sieve into two baskets, the first basket in the size of the persimmon is smaller than the standard, the second basket in the size of the persimmon is larger than the standard,

And then on the divided two baskets, performing the same filter, to the end will be formed, a basket in the case of a persimmon, this situation is a recursive termination condition, do not need to continue to filter.

The essence of the algorithm is to filter by standard:

1, determine the list of the first element as a standard value, starting from the end of the table to find the first one less than this standard value of element A, and the table header element Exchange (this ensures that the elements after the a element are greater than the standard value).

2. After the first step is completed, the position of the standard element is changed to the position of the original element A (that is, the first element of the table is less than the standard value of the position), then from the second element to the position of the standard element, there may be more than the standard value of the element, we need to find out, let this element Starting with the second element, find the first element b that is greater than the standard value, and go to the standard element position (this guarantees that the elements before the B element are less than the standard value).

3, for the middle part of the unfiltered element list (at this time, its first element is a standard element), also perform steps 1 and 2. It can be executed in a loop or recursively, and the terminating condition is the unfiltered part of the list with a length of 1, that is, only one element.

The general idea is to change the right side of the element that is smaller than the standard value to the left and the element on the left that is larger than the standard value to the right. The goal is to divide the list into two parts, the left is small (than the standard), the right side is larger (than the standard).

As a matter of fact, from the first element to the right, the first element that is larger than the standard value is found, and then the first element that is less than the standard value is found from the last element, and then the two are exchanged,

The selection is then performed recursively on the unfiltered interval until the interval length is 1.

C Code Implementation

Complete code as follows URL

Https://github.com/fanqingsong/code-snippet/blob/master/C/QuickSort/quicksort.c

The core code is given below

After porting the list API, the list-based linked list sorts the core code:

/*********************************************************************** QuickSort Functi on************************************************************************///List Quick Sort core functionvoid_list_quicksort (Pt_list_linknode ptlinkfirst, Pt_list_linknode ptlinklast) {//Center node that'll partion list into the//Left nodes all is less than it,//Right nodes all is greater than itPt_list_linknode Ptlinkpivot =NULL; Char* Szpivot =NULL; //The left and right cursor used in one comparing procedurePt_list_linknode Ptlinkleft =NULL; Pt_list_linknode Ptlinkright=NULL; Pt_node Ptnodepivot=NULL; Pt_node Ptnodeleft=NULL; Pt_node Ptnoderight=NULL; //recurse to the ceasing condtion,//One node is the list, and list is ordered.    if(Ptlinkfirst = =ptlinklast) {        return ; }    //Cursor InitializationPtlinkleft =Ptlinkfirst; Ptlinkright=Ptlinklast; //Select first node as the pivot (center pointer)Ptlinkpivot =Ptlinkleft; Ptnodepivot=list_entry (Ptlinkpivot, T_node, Tlinknode); Szpivot= ptnodepivot->str;  while(ptlinkleft!=ptlinkright) {        //Search first node less than pivot from right end         while(ptlinkleft!=ptlinkright) {Ptnoderight=list_entry (Ptlinkright, T_node, Tlinknode); //Find it            if(strcmp (PTNODERIGHT-&GT;STR, Szpivot) <0 )            {                //Save the string to pivot pointer node//Note, this time pivot pointer is ptlinkleftPtnodeleft =list_entry (Ptlinkleft, T_node, Tlinknode); Ptnodeleft->str = ptnoderight->str; //Now pivot node was less than Szpivot, so ptlinkleft node isn't pivot any more, should set Ptlinkleft to its next nod EPtlinkleft = ptlinkleft->Next; //Right searching                 Break; }            //Not found yet            Else            {                //set right node to it previous node, for next comparingPtlinkright = ptlinkright->prev; }        }        //Search first node greater than pivot from left end         while(ptlinkleft!=ptlinkright) {Ptnodeleft=list_entry (Ptlinkleft, T_node, Tlinknode); //Find it            if(strcmp (PTNODELEFT-&GT;STR, Szpivot) >0 )            {                //Save the string to pivot pointer node,//note After first while, Ptnodepivot is Ptlinkrightptnoderight=list_entry (Ptlinkright, T_node, Tlinknode); Ptnoderight->str = ptnodeleft->str; //Now pivot node was greater than Szpivot, so ptlinkright node was not pivot any further, should set Ptlinkright to its pre vious nodePtlinkright = ptlinkright->prev; //Left searching                 Break; }            //Not found yet            Else            {                //set right node to it next node, for next comparingPtlinkleft = ptlinkleft->Next; }        }    }    //Now Center pointer Node (pivot) is ptlinkleft, which are equal to Ptlinkright//Save Pivot Node stringPtlinkpivot =Ptlinkleft; Ptnodepivot=list_entry (Ptlinkpivot, T_node, Tlinknode); Ptnodepivot->str =Szpivot; //Now recursively, quick sort pivot left list    if(Ptlinkpivot! =Ptlinkfirst) {_list_quicksort (Ptlinkfirst, Ptlinkpivot-prev); }    //Now recursively, quick sort pivot right list    if(Ptlinkpivot! =ptlinklast) {_list_quicksort (Ptlinkpivot-Next, Ptlinklast); }}voidquicksortlist (Pt_list_linknode ptlisthead) {Pt_list_linknode Ptlinkfirst=NULL; Pt_list_linknode Ptlinklast=NULL; if(Islistempty (Ptlisthead)) {return ; } Ptlinkfirst= ptlisthead->Next; Ptlinklast= ptlisthead->prev; _list_quicksort (Ptlinkfirst, ptlinklast);}

a summary of experience of macro function definition and pointer relationship

The debugging process found a recursive loop, and the final verification was problematic for the defined list macro (List_add_head insert element in the header):

The definition of inserting a new node between nodes in any of the two adjacent locations of a linked list is as follows:

If the list is empty for the If branch, Prev Next is the linked list header

Else branch processing, the list is not empty case.

//Insert new link node between previous link node and next link node//NOTE:IF clause is must item to add node to empty list, otherwise list_add_tail error#define_list_add (NewLink, Prevlink, NextLink) do{\(NewLink)->next =(NextLink); (NewLink)->prev =(Prevlink); if((prevlink) = =(NextLink)) {(Prevlink)->next =(NewLink); (Prevlink)->prev =(NewLink); }Else{(prevlink)->next =(NewLink); (NextLink)->prev =(NewLink); }                        }  while(0)

The List_add_head macros that are problematic are as follows:

// Add new list node to  list head#define list_add_head (Ptlisthead, ptlistnewlink) do {\                        _ List_add (Ptlistnewlink), (Ptlisthead), (Ptlisthead)->next);                          while (0)

The list is empty no problem, when the list is not empty, then this notation, is replaced by _list_add, where the Else branch is not replaced by

It can be seen that (ptlisthead)->next originally refers to the next node representing the head, but after being replaced because of its basis, resulting in (ptlisthead)->next value is modified to the newly inserted node,

A semantic error is generated!!

                        }Else{                            (ptlisthead)->next = (newLink);                            ((Ptlisthead)->next) ->prev = (NewLink);                        } \

Fix the method, do not place the pointer expression in the argument of the number of macro rows, instead of the pointer variable, that is, the reference pointer directly refers to the target node, to avoid relying on the pointer values of other nodes:

After this is replaced, there is no problem for you, because the entry is directly representative of the corresponding node.

// Add new list node to  list head#define list_add_head (Ptlisthead, ptlistnewlink) do {\                         = (ptlisthead);                         = (ptlisthead),next;                        _list_add (Ptlistnewlink), (Ptprevlink), (Ptnextlink));                          while (0)

View the Linux kernel implementation of the linked list as a function, using inline functions, you can avoid the macro function parameters (pointer expression) is replaced after the semantic confusion, that is, to avoid the side effects of macros:

http://blog.csdn.net/sunweizhong1024/article/details/7586383

/** * List_add_tail-add A new entry * @new: new entry to being added * @head: List head to add it before * * Insert a new Entry before the specified head. * This was useful for implementing queues. */Static__inline__voidList_add_tail (structList_head *_new,structList_head *head) {__list_add (_new, head-prev, head);}/** Insert A new entry between, known consecutive entries. * * This is only for internal list manipulation where we Know * The Prev/next entries already! */Static__inline__void__list_add (structList_head *_new,structList_head *Prev,structList_head *next) {Next->prev =_new; _new->next =Next; _new->prev =prev; Prev->next =_new;}

Algorithm--Quick sort (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.