1
+
2
+ // Libraries to be added
3
+
1
4
#include < iostream>
2
5
#include < cstdlib>
3
6
#include < iomanip>
7
+ #include < chrono>
4
8
#include < math.h>
5
9
#include < time.h>
6
10
#include < fstream>
7
11
8
12
using namespace std ;
13
+
14
+ // Function Prototypes
15
+
9
16
void MergeSort (int array[], int start, int end);
10
17
void Merge (int array[], int p, int q, int r);
11
18
void RandomArray (int array[], int size);
19
+
12
20
int main ()
13
21
{
14
22
int size;
15
23
cout << " Enter the Size of Array: " ;
16
24
cin >> size;
17
25
int *A = new int [size];
26
+
27
+ // To generate random Numbers and store them
28
+
18
29
srand (time (NULL ));
19
30
RandomArray (A, size);
20
31
21
- /* cout << "\n Numbers before Sorting\n to print them, ";
22
- system("pause");
23
- for (int i = 0; i < size; i++)
24
- cout << A[i] << endl;
25
- */
26
- clock_t start, end;
27
- cout << " check1\n " ;
28
- start = clock ();
32
+ // Code to call MergeSort and measure time duration
33
+
34
+ auto start = chrono::high_resolution_clock::now ();
29
35
MergeSort (A, 0 , size - 1 );
30
- end = clock ();
31
- cout << " check2\n " ;
32
- float time_taken = float (end - start) / float (CLOCKS_PER_SEC);
33
- cout << " \n Time taken by the Merge Sort,\n with " << size << " size of Array is: " ;
34
- cout << fixed << time_taken << setprecision (7 ) << " seconds" << endl;
36
+ auto end = chrono::high_resolution_clock::now ();
37
+ double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count ();
38
+
39
+ // Code to calculate the time duration
40
+
41
+ time_taken *= 1e-9 ;
42
+ cout << " \n Time taken by the Merge Sort, with " << size << " size of Array is: " ;
43
+ cout << fixed << time_taken << setprecision (9 ) << " seconds" << endl;
44
+
45
+ // Code to Save sorted array in csv file
35
46
36
47
ofstream OutData;
37
48
OutData.open (" SortedMergeSort.csv" );
38
49
for (int i = 0 ; i < size; i++)
39
50
OutData << A[i] << endl;
40
51
41
- /* cout << "\n\n Numbers after Sorting\n To print them, ";
42
- system("pause");
43
- for (int i = 0; i < size; i++)
44
- cout << A[i] << endl;*/
45
-
46
52
delete[] A;
47
53
return 0 ;
48
54
}
@@ -54,11 +60,15 @@ void MergeSort(int arr[], int startIndex, int endIndex)
54
60
if (startIndex < endIndex)
55
61
{
56
62
int q = floor ((startIndex + endIndex) / 2 );
63
+ // To divide the unsorted Array
57
64
MergeSort (arr, startIndex, q);
58
65
MergeSort (arr, q + 1 , endIndex);
66
+ // To merge the sorted array
59
67
Merge (arr, startIndex, q, endIndex);
60
68
}
61
69
}
70
+
71
+ // Merge function to sort and merge arrays
62
72
void Merge (int arr[], int p, int q, int r)
63
73
{
64
74
int n1 = q - p + 1 ;
@@ -92,6 +102,7 @@ void Merge(int arr[], int p, int q, int r)
92
102
delete[] Left;
93
103
delete[] Right;
94
104
}
105
+
95
106
// RandomArray Function to fill the array with random numbers
96
107
void RandomArray (int array[], int size)
97
108
{
0 commit comments