📌  相关文章
📜  链表合并排序的C程序

📅  最后修改于: 2021-05-28 02:16:36             🧑  作者: Mango

合并排序通常是对链表进行排序的首选。链表的随机访问性能较慢,使得其他一些算法(例如quicksort)的性能较差,而其他算法(例如堆排序)则完全不可能。
排序图像

令head是要排序的链表的第一个节点,而headRef是指向head的指针。请注意,我们需要在MergeSort()中引用head,因为以下实现会更改下一个链接以对链接列表进行排序(而不是节点上的数据),因此,如果原始head上的数据不是最小值,则必须更改head节点。在链接列表中。

MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List 
    then return.
2) Else divide the linked list into two halves.  
      FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
      MergeSort(a);
      MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here) 
   and update the head pointer using headRef.
     *headRef = SortedMerge(a, b);