[Happy DSA] 如何对单链表进行快速排序

来源:互联网 发布:java webserver开发 编辑:程序博客网 时间:2024/05/18 01:49

之前有一篇文章介绍了glib库中单双向链表的排序采用了归并排序,并且不需要额外的空间,这篇文章将介绍c-algorithms库中单双向链表的快速排序过程:

通常快速排序算法都是施行于数组,但它也可以作用于单链表(这里以单向链表为例)。

原理跟数组快速排序是一样的,先partition,然后再递归的解决子单链表的快速排序。
以下是从c-algorithms代码中摘下来的代码段:

static SListEntry *slist_sort_internal(SListEntry **list,                                        SListCompareFunc compare_func){     SListEntry *pivot;     SListEntry *rover;     SListEntry *less_list, *more_list;     SListEntry *less_list_end, *more_list_end;          /* If there are less than two entries in this list, it is     * already sorted */     if (*list == NULL || (*list)->next == NULL) {          return *list;     }     /* The first entry is the pivot */     pivot = *list;     /* Iterate over the list, starting from the second entry.  Sort     * all entries into the less and more lists based on comparisons     * with the pivot */     less_list = NULL;     more_list = NULL;     rover = (*list)->next;     while (rover != NULL) {          SListEntry *next = rover->next;          if (compare_func(rover->data, pivot->data) < 0) {               /* Place this in the less list */               rover->next = less_list;               less_list = rover;          } else {               /* Place this in the more list */               rover->next = more_list;               more_list = rover;          }          rover = next;     }     /* Sort the sublists recursively */     less_list_end = slist_sort_internal(&less_list, compare_func);     more_list_end = slist_sort_internal(&more_list, compare_func);     /* Create the new list starting from the less list */     *list = less_list;     /* Append the pivot to the end of the less list.  If the less list     * was empty, start from the pivot */     if (less_list == NULL) {          *list = pivot;     } else {          less_list_end->next = pivot;     }     /* Append the more list after the pivot */     pivot->next = more_list;     /* Work out what the last entry in the list is.  If the more list was      * empty, the pivot was the last entry.  Otherwise, the end of the      * more list is the end of the total list. */     if (more_list == NULL) {          return pivot;     } else {          return more_list_end;     }}void slist_sort(SListEntry **list, SListCompareFunc compare_func){     slist_sort_internal(list, compare_func);}

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 洗衣机顶盖的安全开关损坏怎么办 苹果平板电脑拍照坏了怎么办 苹果hom键不灵了怎么办 平板电脑home键发烫怎么办 华为平板无法输入资料怎么办 安卓平板没声音怎么办? 平果手机充不了电怎么办 苹果6s用电太快怎么办 平板充不起电了怎么办 日本买的电器国内售后怎么办 海淘地址试投不成功怎么办 怀孕了吐得厉害怎么办 玩网页游戏好卡怎么办 网页游戏占cpu高怎么办 微信有余额绑定其他名下怎么办 银行卡绑定支付余额不对怎么办 可乐机不制冷了怎么办 被淘宝卖家威胁怎么办 征信不好想贷款怎么办 急用钱征信不好怎么办 急用钱逾期不还怎么办 急用钱借款不还怎么办 做b超按压疼痛怎么办 做b超没有尿怎么办 b超憋不到尿怎么办 做b超前没有尿意怎么办 肝胆b超前喝水了怎么办 肝胆彩超喝水了怎么办 胆囊b超喝了水怎么办 系统b超照不到怎么办 思维彩超宝宝不动怎么办 怀孕七个月胎儿缺氧怎么办 怀孕29周小孩偏小怎么办 孕29周胎儿臀位怎么办 刚怀孕有囊肿该怎么办 食杏中毒怎么办吃什么 猫吃了扁桃仁怎么办 夏天来了??点狐臭怎么办? 我有一小点狐臭怎么办 淘客网站被微信屏蔽怎么办 微信老是屏蔽网站怎么办