Classical algorithm Learning--chain list for bubble sorting

Source: Internet
Author: User

In my previous blog, "Classic algorithm learning-bubble sort", I simply implemented the use of arrays for bubbling sorting. This blog we will achieve the future use of the list how to sort, in fact, the whole idea is the same. The sample code is 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 subsequent data, will be two data exchange;

(2) so that the No. 0 data of the array to N-1 data after a single traversal, the largest one of the data to the last position, that is, subscript N-1 position (sank to the bottom).

(3) n = N-1, if n is not 0 repeats (1) (2) Two steps, otherwise the sorting is completed, that is, the array of the NO. 0 data to N-2 data again to traverse;

The core code is as follows:

Linked list implementation bubble sort node *bubblesortlinkedlist (node *pnode) {    if (Pnode = = NULL) {        printf ("%s function executed, list empty, bubble sort failed \ n", __ FUNCTION__);        return NULL;    } else{        Node *pmove;        Pmove = Pnode;        Required (n-1) traversal, number of controls        int size = sizelist (pnode);        for (int i = 0; i < size; i++) {while            (pmove->next! = NULL) {                if (Pmove->element > PMOVE->NEXT-&G t;element) {                    //As long as the element value of the two nodes is exchanged, the int temp can be used                    ;                    temp = pmove->element;                    Pmove->element = pmove->next->element;                    pmove->next->element = temp;                }                Pmove = pmove->next;            }            At the end of each traversal, Pmove moves back to the list header            pmove = Pnode;        }    }    printf ("%s function execution, list bubble sort complete \ n", __function__);    return pnode;}


Classical algorithm Learning--chain list for bubble sorting

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.