[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);}
- [Happy DSA] 如何对单链表进行快速排序
- [Happy DSA] 将已排序的元素序列快速的插入到stl set中
- 利用快速排序对单链表进行排序
- 对文件进行DSA数字签名
- 对数组进行快速排序
- 如何对DataSet进行排序
- 单链表进行快速排序
- 对动态数组进行快速排序
- 对整形数组进行快速排序
- [Happy DSA] rope算法学习
- Go语言对数组进行冒泡排序和快速排序
- 如何对ListView的项进行排序
- 如何对DataTable 进行检索和排序
- 如何对ListView的项进行排序
- 如何对DataTable进行检索和排序
- 如何对DataTable进行检索和排序
- 如何对ListView的项进行排序
- 如何对DataTable进行检索和排序
- lucene用indexReader获取某个Document中的所有域的名字
- 基于RBAC的权限设计模型
- super.onCreate(savedInstanceState)
- Linux 解压缩与管道命令
- struts 零配置demo(struts-convertion-plugin)
- [Happy DSA] 如何对单链表进行快速排序
- 苹果新手Mac OS X 使用笔记--------显示桌面,切换程序
- [Qt教程] 第45篇 进阶(五)Qt样式表
- 职场成功要素:1个目标,2个基点,3大技巧,4项理念,5分运气,6项要求,7分学习,8分交际,9分习惯,10分自信,11个陷阱,12分努力 《摘录》
- 大三下学期到大四上学期的IT学习规划
- MCITP考试简介(服务器方向)
- 【HP 大中华区总裁孙振耀的退休感言】
- 经典语录,精彩改变你一生!
- 可以让你少奋斗10年的工作经验