-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
shuffle.h
44 lines (39 loc) · 913 Bytes
/
shuffle.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* FISHER YATES'S SHUFFLE
*
* Features:
* 1. shuffle list in O(n) time.
*
* http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*
******************************************************************************/
#ifndef ALGO_SHUFFLE_H__
#define ALGO_SHUFFLE_H__
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
namespace alg {
/**
* shuffle the 'list' of length 'len'
*/
template<typename T>
static void shuffle(T * list, int len) {
srand(time(NULL));
int i = len, j;
T temp;
if ( i == 0 ) return;
while ( --i ) {
j = rand() % (i+1);
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
#endif //