Single linked list (not the leading node) to achieve bubble sort __.

Source: Internet
Author: User

I made a simple bubble sort using an array in my previous blog, "Bubble sorting." This blog we will implement the use of single linked list How to sort, in fact, the whole idea is the same. Sample code uploaded to: https://github.com/chenyufeng1991/BubbleSortLinkedList.

The algorithm is described as follows:

(1) Compare the adjacent two data, if the previous data is greater than the following data, will be two data exchange;

(2) so that the No. 0 data of the array to N-1 data for one traversal, the largest data to the last position, which is labeled as N-1 position (sank to the bottom).

(3) n = N-1, if n is not 0 to repeat (1) (2) Two steps, otherwise sorting is completed, that is, the No. 0 data of the array to N-2 data again to traverse; The core code is as follows:

List implementation Bubble sort
node *bubblesortlinkedlist (node *pnode) {
    if (Pnode = NULL) {
        printf ("%s function execution, linked list is empty, bubble sort failed \ n", _ _FUNCTION__);
        return NULL;
    } else{

        Node *pmove;
        Pmove = Pnode;
        Requires (n-1) traversal, control times
        int size = sizelist (pnode);
        for (int i = 0; i < size, i++) {while
            (Pmove->next!= NULL) {
                if pmove->element > pmove->next-& gt;element) {
                    ///As long as the element value of the two nodes is exchanged,
                    int temp;
                    temp = pmove->element;
                    Pmove->element = pmove->next->element;
                    pmove->next->element = temp;
                }
                Pmove = pmove->next;
            }
            At the end of each traversal, the Pmove is moved back to the list head
            pmove = Pnode;
        }
    printf ("%s function execution, linked list bubbling sort complete \ n", __function__);

    return pnode;
}


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.