1
+ = == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
2
+ Time calculation for bubble sort and selection sort .
3
+
4
+ #include <stdio.h>
5
+ #include <time.h> //To include clock function (used to calculate time taken by function
6
+
7
+
8
+ void bubble_sort (int A [],int n ) //Function to perform bubble sort
9
+ {
10
+ int i ,j ,temp ;
11
+ for (i = 0 ;i < n - 1 ;i ++ )
12
+ {
13
+ for (j = 0 ;j < n - i - 1 ;j ++ )
14
+ {
15
+ if (A [j ]> A [j + 1 ])
16
+ {
17
+ temp = A [j + 1 ];
18
+ A [j + 1 ] = A [j ];
19
+ A [j ] = temp ;
20
+ }
21
+ }
22
+ }
23
+ for (i = 0 ;i < n ;i ++ ) //To print sorted array
24
+ {
25
+ printf ("%d" ,A [i ]," , " );
26
+ printf (" , " );
27
+ }
28
+ }
29
+
30
+ void selection_sort (int A [],int n ) //Function to perform selection sort
31
+ {
32
+ int i ,j ,temp ;
33
+ for (i = 0 ;i < n - 1 ;i ++ )
34
+ {
35
+ for (j = i + 1 ;j < n ;j ++ )
36
+ {
37
+ if (A [j ]< A [i ])
38
+ {
39
+ temp = A [i ];
40
+ A [i ] = A [j ];
41
+ A [j ] = temp ;
42
+ }
43
+ }
44
+ }
45
+ for (i = 0 ;i < n ;i ++ ) //To print sorted array
46
+ {
47
+ printf ("%d" ,A [i ]);
48
+ printf (" , " );
49
+ }
50
+ }
51
+
52
+ int main ()
53
+ {
54
+ int n ,i ;
55
+ clock_t st ,en ;
56
+ double t ;
57
+ printf ("Enter size of the array: " );
58
+ scanf ("%d" ,& n );
59
+ int A [n ];
60
+ for (i = 0 ;i < n ;i ++ ) //Input of array
61
+ {
62
+ printf ("\nEnter the %d element of the array: " ,i + 1 );
63
+ scanf ("%d" ,& A [i ]);
64
+ }
65
+ int B [n ];
66
+ for (i = 0 ;i < n ;i ++ ) //Making 2 copies of entered array – one for bubble sort
67
+ B [i ]= A [i ]; // and another for selection sort
68
+ st = clock (); //starting of clock
69
+ bubble_sort (A ,n ); //calling bubble sort function
70
+ en = clock (); //ending of clock 1
71
+ t = (double )(en - st )/CLOCKS_PER_SEC ; //time elapsed for bubble sort
72
+ printf ("Time taken for Bubble sort is :%f \n" ,t );
73
+ st = clock (); //clock for selection sort
74
+ selection_sort (B ,n ); //function calling
75
+ en = clock (); //ending of clock 2
76
+ t = (double )(en - st )/CLOCKS_PER_SEC ; //time elapsed for selection sort
77
+ printf ("Time taken for Selection sort is :%f \n" ,t );
78
+ return 0 ;
79
+ }
80
+
81
+
82
+ = == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
0 commit comments