-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBubbleSortByStep.java
More file actions
52 lines (47 loc) · 1.83 KB
/
BubbleSortByStep.java
File metadata and controls
52 lines (47 loc) · 1.83 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
package AlgorithmSort;
import java.util.Scanner;
public class BubbleSortByStep {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter list size:");
int size = scanner.nextInt();
int[] list = new int[size];
System.out.println("Enter " + list.length + " values:");
for (int i = 0; i < list.length; i++) {
list[i] = scanner.nextInt();
}
System.out.print("Your input list: ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + "\t");
}
System.out.println("\nBegin sort processing...");
bubbleSortByStep(list);
}
public static void bubbleSortByStep(int[] list) {
boolean needNextPass = true;
for (int k = 1; k < list.length && needNextPass; k++) {
needNextPass = false;
for (int i = 0; i < list.length - k; i++) {
if (list[i] > list[i + 1]) {
/* Swap list[i] with list[i + 1] */
System.out.println("Swap " + list[i] + " with " + list[i + 1]);
int temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
needNextPass = true; /* Next pass still needed */
}
}
/* Array may be sorted and next pass not needed */
if (needNextPass == false) {
System.out.println("Array may be sorted and next pass not needed");
break;
}
/* Show the list after sort */
System.out.print("List after the " + k + "' sort: ");
for (int j = 0; j < list.length; j++) {
System.out.print(list[j] + "\t");
}
System.out.println();
}
}
}