【发布时间】:2016-01-10 06:19:01
【问题描述】:
我很难理解 Skiena 的快速排序。具体来说,他在用partition函数,尤其是firsthigh参数做什么?
quicksort(item_type s[], int l, int h) {
int p; /* index of partition */
if ((h - l) > 0) {
p = partition(s, l, h);
quicksort(s, l, p-1);
quicksort(s, p+1, h);
}
}
我们可以通过维护数组的三个部分将数组划分为特定枢轴元素的一次线性扫描:小于枢轴(
firsthigh左侧),大于或等于枢轴(@987654325 之间) @ 和i),未探索(在i的右侧),实现如下:
int partition(item_type s[], int l, int h) {

int i; /* counter */
int p; /* pivot element index */
int firsthigh; /* divider position for pivot element */
p = h;
firsthigh = l;
for (i = l; i <h; i++) {
if (s[i] < s[p]) {
swap(&s[i],&s[firsthigh]);
firsthigh ++;
}
swap(&s[p],&s[firsthigh]);
return(firsthigh);
}
【问题讨论】:
-
firsthigh是不小于s[p]的第一个(即最左、最低的索引)元素的索引。你试过用铅笔和纸跑partition(...)吗?
标签: c algorithm sorting quicksort