File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Scanner ;
2+
3+ public class BubbleSort {
4+
5+ public static int [] arrInput (Scanner sc ) {
6+ System .out .print ("Enter the size of the array: " );
7+ int n = sc .nextInt ();
8+ int [] arr = new int [n ];
9+ System .out .println ("Enter the elements of the array: " );
10+ for (int i = 0 ; i < n ; i ++) {
11+ arr [i ] = sc .nextInt ();
12+ }
13+ return arr ;
14+ }
15+
16+ public static void bubbleSort (int [] arr ) {
17+ int n = arr .length ;
18+ for (int i = 0 ; i < n - 1 ; i ++) {
19+ for (int j = 0 ; j < n - i - 1 ; j ++) {
20+ if (arr [j ] > arr [j + 1 ]) {
21+ // swap arr[j] and arr[j+1]
22+ int temp = arr [j ];
23+ arr [j ] = arr [j + 1 ];
24+ arr [j + 1 ] = temp ;
25+ }
26+ }
27+ }
28+ }
29+
30+ public static void main (String [] args ) {
31+ Scanner sc = new Scanner (System .in );
32+
33+ int [] arr = arrInput (sc );
34+
35+ System .out .print ("Array before sorting: " );
36+ for (int num : arr ) {
37+ System .out .print (num + " " );
38+ }
39+ System .out .println ();
40+
41+ bubbleSort (arr );
42+
43+ System .out .print ("Array after sorting: " );
44+ for (int num : arr ) {
45+ System .out .print (num + " " );
46+ }
47+ System .out .println ();
48+
49+ sc .close ();
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments