数组随机化与顺序文件随机样本选择算法
1. 数组随机化算法
1.1 随机化函数实现
以下是一个用于随机化数组元素顺序的函数模板:
template <class otype>
void randomize (otype a[], int first, int last)
{
int n = last - first + 1;
// Number of cells in a[first..last]
otype temp[n];
// Need an extra storage array.
int r = randint(0, n-1);
// Generate a "shift distance."
for (int j = 0, k = first + r; k <= last; ++k)
temp[j++] = a[k];
// Copy back part of "a" to front of "temp"
for (int k = first; k <= first + r - 1; ++k)
temp[j++] = a[k];
// Copy front part of "a" to back of "temp"
// Copy all of "temp" back to a[first..last]
for (int j = 0, int k = first; k <= last; ++j, ++k)
a[k] = temp[j++];
超级会员免费看
订阅专栏 解锁全文
356

被折叠的 条评论
为什么被折叠?



