Partition 函数的三种实现方式:
/*此为算法分析与设计的版本*/
int partition(int a[],int start,int end)
{
//int r=rand1(start,end);
//swap(a[start],a[r]);
int i=start,j=end+1;
int x=a[i];
while(1)
{
while(a[++i]<x&&i<end);
while(a[--j]>x);
if(i>=j)
break;
swap(a[i],a[j]);
}
a[start]=a[j];
a[j]=x;
return j;
}
下面是算法导论上的版本
/*此为算法导论上的版本*/
int partition2(int a[],int start,int end)
{
int x=a[end];
int i=start-1,j;
for(j=start;j<end;j++)
{
if(a[j]<=x)
{
i++;
swap(a[i],a[j]);
}
}
swap(a[i+1],a[end]);
return i+1;
}严蔚敏老师的数据结构(C语言版)上的实现:
/*此为数据结构上的版本*/
int partition3(int a[],int start,int end)
{
int key = a[start];//key初始化为a的首元素
while(start<end)
{
while(start<end && a[end]>=key) end--;
a[start] = a[end];
while(start<end && a[start]<=key) start++;
a[end]=a[start];
}
a[start]=key;
return start;
}
4万+

被折叠的 条评论
为什么被折叠?



