teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

書き換え

2018/04/28 05:53

投稿

katoy
katoy

スコア22328

answer CHANGED
@@ -1,47 +1,60 @@
1
1
  ```java
2
+ import java.util.ArrayList;
2
- public class IntBubbleSorter {
3
+ import java.util.Collections;
3
- final static int REPEAT_COUNT = 3;
4
+ import java.util.List;
4
- final static int ARRAY_SIZE = 100;
5
+ import java.util.Random;
5
6
 
7
+ public class Kadai03_3 {
8
+ private static final int NUM_NUMBER = 100;
6
9
  public static void main(String[] args) {
7
- int count = 0;
10
+ System.out.println("乱数100個 0~100)");
8
- int[] array = new int[ARRAY_SIZE];
11
+ int[] numbers = new int[NUM_NUMBER];
12
+ Random rand = new Random();
9
13
 
10
- for (int i = 0; i < REPEAT_COUNT; i++) {
14
+ for (int i = 0; i < numbers.length; i++) {
11
- int comp = bubbleSort(randum_array(array));
15
+ numbers[i] = rand.nextInt(100);
16
+ if (i % 10 == 0) {
17
+ System.out.print("\n");
18
+ }
12
- System.out.println("number of comparison in bubble sort: " + comp);
19
+ System.out.print(numbers[i] + "\t");
13
- count += comp;
14
20
  }
15
- System.out.println("平均比較回数:" + 1.0 * count / REPEAT_COUNT);
21
+ int min_num = Integer.MAX_VALUE;
22
+ int max_num = Integer.MIN_VALUE;
16
- }
23
+ double total = 0;
17
24
 
18
- public static int[] randum_array(int[] array) {
19
- for (int i = 0; i < array.length; i++) {
25
+ for (int i = 0; i < numbers.length; i++) {
20
- array[i] = (int)(Math.random() * 101);
26
+ if (numbers[i] < min_num) {
27
+ min_num = numbers[i];
28
+ }
29
+ if (max_num < numbers[i]) {
30
+ max_num = numbers[i];
31
+ }
32
+ total += numbers[i];
21
33
  }
22
- return array;
34
+ double ave_num = total / numbers.length;
23
- }
24
35
 
36
+ System.out.print("\n");
37
+ System.out.println("最小値:" + min_num);
25
- public static int bubbleSort(int[] array) {
38
+ System.out.println("最大値:" + max_num);
26
- int lastPos;
27
- int index;
28
- int temp;
29
- int comp = 0;
39
+ System.out.println("平均値:" + ave_num);
30
40
 
31
- for (lastPos = array.length - 1; lastPos >= 0; lastPos--) {
41
+ List<Integer> list = new ArrayList<>(numbers.length);
32
- for (index = 0; index <= lastPos - 1; index++) {
33
- if (array[index] > array[index + 1]) {
34
- comp++;
35
- temp = array[index];
36
- array[index] = array[index + 1];
37
- array[index + 1] = temp;
42
+ for (int x : numbers) {
38
- }
43
+ list.add(x);
39
- }
40
44
  }
45
+ min_num = Collections.min(list);
46
+ max_num = Collections.max(list);
47
+ total = 0;
48
+ for (int x : list) {
41
- return comp;
49
+ total += x;
50
+ }
51
+ ave_num = total / numbers.length;
52
+
53
+ System.out.print("\n");
54
+ System.out.println("最小値:" + min_num);
55
+ System.out.println("最大値:" + max_num);
56
+ System.out.println("平均値:" + ave_num);
42
57
  }
43
58
  }
44
-
45
59
  ```
46
- 実行例:
47
- ![イメージ説明](eba0d0747a528b093eea2067461d692f.png)
60
+ ![イメージ説明](9c9b1b4cbdb25b99eaa694254bd09085.png)