算法F2,比算法S更有效率,但几乎同样简洁。
算法F2
- initialize set S to empty
- for J := N - M + 1 to N do
- T := RandInt(1, J)
- if T is not in S then
- insert T in S
- else
- insert J in S
随机排列
下面是Floyd的算法P。
算法P
- initialize sequence S to empty
- for J := N - M + 1 to N do
- T = RandInt(1, J)
- if T is not in S then
- prefix T to S
- else
- insert J in S after T
C++实现
#include <iostream>
#include <set>
#include <vector>
using namespace std;
set<int> s;
vector<int> s2;
void F2(int n,int m){
s.clear();
for(int i=n-m+1;i<=n;i++){
int t=rand()%i+1;
if(s.find(t) == s.end()){
s.insert(t);
}else
s.insert(i);
}
}
void p(int n,int m){
s2.clear();
for(int i=n-m+1;i<=n;i++){
int t=rand()%i+1;
bool flag = false;
vector<int>::iterator iter=s2.begin();
for(;iter!=s2.end() && (*iter)!=t;iter++);//寻找s2中是否存在t
if(iter == s2.end()){
s2.insert(s2.begin(),t);
}else
s2.insert(++iter,i);
}
}
int main(){
int t=10;
while(t>0){
F2(10,5);
set<int>::iterator iter=s.begin();
for(;iter!=s.end();iter++){
cout<<(*iter)<<" ";
}
cout<<endl;
t--;
}
p(10,5);
vector<int>::iterator iter2=s2.begin();
for(;iter2!=s2.end();iter2++){
cout<<(*iter2)<<" ";
}
return 0;
}