【发布时间】:2026-02-14 22:20:03
【问题描述】:
下面的随机选择程序找不到第 i 个顺序统计。以下程序遵循 Cormen 的算法简介中提供的算法。提前感谢您发现错误。
#include<stdio.h>
#include<stdlib.h>
int random(int a,int b) //generates random numbers [a,b]
{
return a+(rand()%(b-a+1));
}
void swap(int *a,int *b) //swwaps the elements
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int partition(int a[],int p,int r) //partitioning similar to that of quicksort
{
int i=p-1,j,x=a[r];
for(j=p;j<r;j++)
{
if(a[i]<x)
{
i++;
swap(&a[i],&a[j]);
}
}
swap(&a[i+1],&a[r]);
return i+1;
}
int random_partition(int a[],int p,int r) //random index generation whose element gets swapped with the last element of the array
{
int q=random(p,r);
swap(&a[q],&a[r]);
return partition(a,p,r);
}
int random_selection(int a[],int p,int r,int index) //finds the i'th order statistic
{
if(p==r)
return a[p];
if(p<r)
{
int mid,k;
mid=random_partition(a,p,r);
k=mid-p+1;
if(k==index)
return a[mid];
if(index<k)
return random_selection(a,p,mid-1,index);
if(index>k)
return random_selection(a,mid+1,r,index);
}
}
main()
{
int a[50],i,size,index;
printf("enter the size of the array\n");
scanf("%d",&size);
printf("enter the array elements\n"); //takes array elements input
for(i=1;i<=size;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=size;i++) //prints the index of each element
{
printf("%d\n",random_selection(a,1,size,i));
}
}
【问题讨论】:
-
我没有看到任何地方...
-
我一直不明白 srand 的目的。你能解释一下吗?
-
哦。我现在知道了。谢谢指出
-
抱歉,我处于离线状态,无法回复。希望您了解 srand 和种子的目的。
-
我按照建议添加了 srand。然而对于 4 个数字的输入,例如 1、4、3、2 和 2 作为索引号,我每次都会得到不同的输出,而不是给出 2 作为二阶统计数据