File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ public class BubbleSort {
4
+ public static void main (String [] args ) {
5
+ Scanner sc = new Scanner (System .in );
6
+ int n = sc .nextInt ();
7
+ int [] arr = new int [n ];
8
+ for (int i = 0 ; i < n ; i ++)
9
+ arr [i ] = sc .nextInt ();
10
+ bubble (arr );
11
+ for (int i : arr ) {
12
+ System .out .print (i + " " );
13
+ }
14
+ sc .close ();
15
+ }
16
+
17
+ public static void bubble (int [] arr ) {
18
+ for (int i = 1 ; i <= arr .length - 1 ; i ++)
19
+ for (int j = 0 ; j < arr .length - i ; j ++)
20
+ if (isSmaller (arr , j + 1 , j ))
21
+ swap (arr , j + 1 , j );
22
+ }
23
+
24
+ public static boolean isSmaller (int [] arr , int i , int j ) {
25
+ System .out .println ("Comparing " + arr [i ] + " with " + arr [j ]);
26
+ if (arr [i ] < arr [j ])
27
+ return true ;
28
+ else
29
+ return false ;
30
+ }
31
+
32
+ public static void swap (int [] arr , int i , int j ) {
33
+ System .out .println ("Swapping " + arr [i ] + " and " + arr [j ]);
34
+ int temp = arr [i ];
35
+ arr [i ] = arr [j ];
36
+ arr [j ] = temp ;
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments