forked from bzdgn/data-structures-in-java
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRandomizatinDemo.java
More file actions
39 lines (30 loc) · 878 Bytes
/
RandomizatinDemo.java
File metadata and controls
39 lines (30 loc) · 878 Bytes
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
package ds_001_intro;
import java.util.concurrent.ThreadLocalRandom;
public class RandomizatinDemo {
public static void main(String[] args) {
int[] intArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
printArray(intArray);
randomizeArray(intArray);
printArray(intArray);
}
private static void printArray(int[] intArray) {
System.out.print("Array: ");
for(int i = 0; i < intArray.length; i++) {
System.out.printf("%2d", intArray[i]);
}
System.out.printf("\n");
}
private static void randomizeArray(int[] intArray) {
for(int i = 0; i < intArray.length; i++) {
// Random number between i and N
int j = getRandom(i, intArray.length);
// swap
int temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
private static int getRandom(int i, int length) {
return ThreadLocalRandom.current().nextInt(i, length);
}
}