这是我写的一个集产生随机字母,二分技术查找,递归全排序的程序

作者在 2010-04-01 09:08:24 发布以下内容
#include<iostream>
#include<time.h>
using namespace std;
const int N=100;
int n,k=0;
char list[N];
int by(const char& x)
{
 int l=0;int r=n;
 while(l<=r)
 {
  int middle=(l+r)/2;
  if(x==list[middle]) return middle;
  if(x>list[middle]) l=middle+1;
  else r=middle-1;
 }
 return -1;
}
void set()
{
 int i,j,k,t,q;
 char temp;
 cout<<"确定产生随机数个数n=";
 cin>>n;
 srand( (unsigned)time( NULL ) );
 for(i=0;i<n;i++)
       list[i]=rand()%26+97;
 for(k=0;k<n-1;k++)
 { q=k;
  for(j=k+1;j<n;j++)
   if(list[j]<list[q]) q=j;
   if(q!=k)
   {temp=list[q];list[q]=list[k];list[k]=temp;}
 }
   cout<<" 产生的随机数为:"<<endl;
   for(t=0;t<n;t++)
   cout<<list[t]<<" ";
   cout<<endl;
}
void perm(char list[],int k)
{
 if(k==n)
 {
  for(int i=0;i<n;i++)
   cout<<list[i];
  cout<<endl;
 }
  else
   for(int i=k;i<n;i++)
   {
    swap(list[k],list[i]);
     perm(list,k+1);
    swap(list[k],list[i]);
   }
}
inline swap(char& a,char& b)
{
 char temp=a;a=b;b=temp;
}
int main()
{
 char x;
 set();
 cout<<"输入查找元素x=";cin>>x;
 int p=by(x);
 if(p==-1)
  cout<<"未找到x"<<endl;
 else
  cout<<"所找元素在第"<<p+1<<"个位置!"<<endl;
 cout<<"全排列结果:"<<endl;
 //perm(list,k);
 return 0;
}
现在有两个问题,1.rand()产生的随机数有重复!2.全排列函数无法处理有相同元素时全排列结果有重复问题!
请高手们指点迷津,寻求最优算法!!!
 
请求赐教 | 阅读 856 次
文章评论,共0条
游客请输入验证码
浏览1648次
最新评论