Skip to content

Commit 82cb610

Browse files
authored
Merge pull request #3 from suiyueranzly/Bubble-Sort
add Bubble Sort on Java
2 parents ee100e7 + 28c8a23 commit 82cb610

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Brute Force/Bubble Sort/Code.java

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import org.algorithm_visualizer.ChartTracer;
2+
import org.algorithm_visualizer.LogTracer;
3+
import org.algorithm_visualizer.Randomize;
4+
5+
import java.util.Arrays;
6+
7+
public class Main {
8+
9+
private static ChartTracer chartTracer = new ChartTracer();
10+
11+
private static LogTracer logTracer = new LogTracer("Console");
12+
13+
private static Integer [] array = (Integer[]) new Randomize.Array1D(15, new Randomize.Integer(1, 20)).create();
14+
15+
public static void main(String[] args) {
16+
17+
int length = array.length;
18+
19+
logTracer.printf("original array = %s\n",Arrays.toString(array));
20+
21+
chartTracer.set(array).delay();
22+
23+
boolean flag;
24+
25+
for (int i = length - 1; i > 0; i--) {
26+
flag = true;
27+
for (int j = 0; j < i; j++) {
28+
chartTracer.select(j).delay();
29+
chartTracer.select(j + 1).delay();
30+
if (array[j] > array[j + 1]) {
31+
logTracer.printf("swap %s and %s \n",array[j],array[j + 1]);
32+
swap(j, j + 1, array);
33+
flag = false;
34+
}
35+
chartTracer.deselect(j);
36+
chartTracer.deselect(j + 1);
37+
}
38+
if (flag) {
39+
break;
40+
}
41+
}
42+
43+
44+
logTracer.printf("\n sorted array = %s",Arrays.toString(array));
45+
46+
}
47+
48+
private static void swap(int x, int y, Integer [] array) {
49+
int temp = array[x];
50+
array[x] = array[y];
51+
array[y] = temp;
52+
chartTracer.patch(x, array[x]).patch(y, array[y]).delay();
53+
chartTracer.depatch(x).depatch(y);
54+
}
55+
56+
}

0 commit comments

Comments
 (0)