1
+ // Bubble Sort, Selection Sort, Insertion Sort
2
+
3
+ import java .util .Random ;
4
+
5
+ public class Practical_1 {
6
+ private static void bubblesort (int size ){
7
+ long start , end ; double c ;
8
+ Random random = new Random ();
9
+ int [] a = new int [size ];
10
+ for (int i = 0 ; i < size ; i ++) {
11
+ a [i ] = random .nextInt (1000 );
12
+ }
13
+ start = System .nanoTime ();
14
+ for (int i = 0 ; i < size - 1 ; i ++) {
15
+ for (int j = 0 ; j < size - i - 1 ; j ++) {
16
+ if (a [j + 1 ] < a [j ]) {
17
+ int t = a [j ];
18
+ a [j ] = a [j + 1 ];
19
+ a [j + 1 ] = t ;
20
+ }
21
+ }
22
+ }
23
+ end = System .nanoTime (); c = (double ) (end - start );
24
+ System .out .println ("\n BUBBLE SORT" );
25
+ System .out .println ("Time:" + c );
26
+ }
27
+
28
+ private static void selectionsort (int size ){
29
+ long start , end ; double c ;
30
+ Random random = new Random ();
31
+ int [] a = new int [size ];
32
+ for (int i = 0 ; i < size ; i ++) {
33
+ a [i ] = random .nextInt (1000 );
34
+ }
35
+ start = System .nanoTime ();
36
+ for (int i = 0 ; i < size - 1 ; i ++) {
37
+ int min = i ;
38
+ for (int j = i + 1 ; j < size ; j ++) {
39
+ if (a [j ] < a [min ]) {
40
+ min = j ;
41
+ }
42
+ }
43
+ int t = a [min ];
44
+ a [min ] = a [i ];
45
+ a [i ] = t ;
46
+ }
47
+ end = System .nanoTime (); c = (double ) (end - start );
48
+ System .out .println ("\n SELECTION SORT" );
49
+ System .out .println ("Time:" + c );
50
+ }
51
+
52
+ private static void insertionsort (int size ){
53
+ long start , end ; double c ;
54
+ Random random = new Random ();
55
+ int [] a = new int [size ];
56
+ for (int i = 0 ; i < size ; i ++) {
57
+ a [i ] = random .nextInt (1000 );
58
+ }
59
+ start = System .nanoTime ();
60
+ for (int i = 1 ; i < size ; i ++) {
61
+ int t = a [i ];
62
+ int j = i - 1 ;
63
+ while (j >= 0 && a [j ] > t ) {
64
+ a [j + 1 ] = a [j ];
65
+ j = j - 1 ;
66
+ }
67
+ a [j + 1 ] = t ;
68
+ }
69
+ end = System .nanoTime (); c = (double ) (end - start );
70
+ System .out .println ("\n INSERTION SORT" );
71
+ System .out .println ("Time:" + c );
72
+ }
73
+ public static void main (String [] args ) {
74
+ int size = 1000 ;
75
+ bubblesort (size );
76
+ selectionsort (size );
77
+ insertionsort (size );
78
+ }
79
+ }
0 commit comments