shuffle实现 / 洗牌算法
目的
随机打乱一个数组
code
#include <bits/stdc++.h>
using namespace std;
void knuth_shuffle(int *arr, int n)
{
for (int i = n - 1; i > 1; i--)
swap(arr[i], arr[rand()%(i-1)]);
swap(arr[1], arr[0]);
}
int main()
{
int arr[256];
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
knuth_shuffle(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}