-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShuffling.java
More file actions
32 lines (28 loc) · 815 Bytes
/
Shuffling.java
File metadata and controls
32 lines (28 loc) · 815 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
import java.util.Random;
public class Shuffling {
private static void swap(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void shuffle(Comparable[] a) {
Random rand = new Random();
int n = a.length;
for (int i = 0; i < n; ++i) {
int j = rand.nextInt(i + 1);
swap(a, i, j);
}
}
public static void print(Object[] array) {
for (Object a : array) {
System.out.print(a + " ");
}
System.out.println("");
}
public static void main(String[] args) {
String[] array = {"Alice", "Bob", "Charlie", "Eve", "Hope"};
Shuffling.print(array);
Shuffling.shuffle(array);
Shuffling.print(array);
}
}