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;
}