-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise6_18.java
More file actions
60 lines (47 loc) · 1.22 KB
/
Exercise6_18.java
File metadata and controls
60 lines (47 loc) · 1.22 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
import java.util.Scanner;
public class Exercise6_18 {
public static void main(String[] args) {
final int NUMBER_LENGTH = 100;
Scanner input = new Scanner(System.in);
double[] number = new double[10];
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
number[i] = input.nextDouble();
}
System.out.println("My list is: ");
printList(number);
bubbleSort(number);
System.out.println("After sort list is: ");
printList(number);
}
public static void bubbleSort(double[] list) {
boolean changed = false;
for (int i = 0; i < 10; i++) {
for (int j = 1; j < 10 - i; j++) {
/* maybe occurs ArrayIndexOutOfBoundsException
if (list[j] > list[j+1]) {
//swap list[j] and list[j+1]
double temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
*/
if (list[j - 1] > list[j]) {
double temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
changed = true;
}
}
if (!changed)
break;
}
}
public static void printList(double[] list) {
for (int i = 0; i < 10; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
}
}