下面的随机选择程序没有找到第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));
}
}
答案 0 :(得分:0)
您的srand()
需要main()
吗?就像这些线程一样
Recommended way to initialize srand?
和How does srand relate to rand function?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, n;
time_t t;
n = 5;
/* Intializes random number generator */
srand((unsigned) time(&t));
/* Print 5 random numbers from 0 to 50 */
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 50);
}
return(0);
}