-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.java
45 lines (37 loc) · 1.1 KB
/
BubbleSort.java
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
import java.util.Scanner;
public class BubbleSort {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Get list from user
double[] myList = new double[10];
System.out.print("Please input 10 numbers: ");
//Input each element
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextDouble();
}
//Apply method
bubbleSort(myList);
//Print the list
System.out.println("The list from lowest to largest is: ");
printList(myList);
}
//Method for printing
static void printList(double[] list) {
for (int i = 0; i < list.length; i++)
System.out.println(list[i]);
}
//Method for sorting
static void bubbleSort(double[] list) {
boolean changed = true;
do {
changed = false;
for (int j = 0; j < list.length - 1; j++)
if (list[j] > list[j+1]) {
double temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
}
}