File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
classical_algorithms/java Expand file tree Collapse file tree 1 file changed +57
-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 scan = new Scanner (System .in );
6
+ try {
7
+ int low ,high ;
8
+ int n ,i ;
9
+ System .out .println ("How many elements do you want in the array?" );
10
+ n =scan .nextInt ();
11
+ int a []= new int [n ];
12
+ System .out .println ("Enter the array elements one by one" );
13
+
14
+ for (i =0 ;i <n ;i ++)
15
+ {
16
+ a [i ]=scan .nextInt ();
17
+ }
18
+ System .out .println ("Array before sorting is:" );
19
+ printArray (a , n );
20
+ low =0 ;
21
+ high =n -1 ;
22
+
23
+ MergeSort obj = new MergeSort ();
24
+ obj .sort (a , low , high );
25
+ System .out .println ();
26
+
27
+ System .out .println ("The sorted array is: " );
28
+ printArray (a , n );
29
+
30
+ }catch (Exception e ){e .printStackTrace ();}
31
+ scan .close ();
32
+ }
33
+
34
+ private static void printArray (int array [], int size ){
35
+ for (int i =0 ; i < size ; i ++){
36
+ System .out .println (array [i ]);
37
+ }
38
+ System .out .println ("\n " );
39
+ }
40
+
41
+ private static void bubbleSort (int array [], int size ){
42
+ for (int i =0 ; i < size - 1 ; i ++){
43
+ for (int j =0 ; j < size - i - 1 ; j ++){
44
+ if (array [j ] > array [j +1 ]){
45
+ swap (array [j ], array [j +1 ]);
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ private static void swap (int a , int b ){
52
+ int temp = a ;
53
+ a = b ;
54
+ b = temp ;
55
+ }
56
+ }
57
+
You can’t perform that action at this time.
0 commit comments