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