-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayHW2.java
More file actions
62 lines (52 loc) · 1.33 KB
/
ArrayHW2.java
File metadata and controls
62 lines (52 loc) · 1.33 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package tw.homework;
public class ArrayHW2 {
int arr[] = new int[42];
int index[] = new int[42];
//隨機產生1~42的數字100000次,計算每個數出現的次數
public void ranArr() {
for (int i = 1; i <= 100000; i++) {
int j = (int) (Math.random() * 42);
arr[j]++;
}
}
public void Index() {
for (int i = 0; i < 42; i++) {
index[i] = i + 1;
}
}
// 起泡排序
public void Sort() {
for (int x = 0; x < arr.length; x++) {
for (int y = x + 1; y < arr.length; y++) {
if (arr[x] > arr[y]) {
int tmp = arr[x];
arr[x] = arr[y];
arr[y] = tmp;
// 索引值
tmp = index[x];
index[x] = index[y];
index[y] = tmp;
}
}
}
}
public static void main(String[] args) {
ArrayHW2 unsort = new ArrayHW2();
ArrayHW2 sorted = new ArrayHW2();
unsort.ranArr();
unsort.Index();
for (int i = 0; i < 42; i++) {
sorted.arr[i] = unsort.arr[i];
sorted.index[i] = unsort.index[i];
}
System.out.println("original data: sorted data:");
System.out.println("-------------- --------------");
sorted.Sort();
for (int j = 0; j < 42; j++) {
System.out.printf(" %2d | %2d %8d | %2d%n", unsort.index[j], unsort.arr[j], sorted.index[j],
sorted.arr[j]);
// System.out.println(unsort.index[j]+" "+unsort.arr[j]+"
// "+sorted.index[j]+" "+sorted.arr[j]);
}
}
}