-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeSort.cpp
132 lines (106 loc) · 1.87 KB
/
mergeSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Sorting
#include<iostream>
#include<ctime>
//#include<cstdlib>
#include<cmath>
using namespace std;
void RandArr(int arr[],int n);
void display_arr(int arr[],int n);
void merge(int arr[],int s,int m,int e);
void mergeSort(int arr[],int s,int e);
void inputArray(int arr[],int n);
int main()
{
clock_t start,end;
int size = 0;
cout<<"Enter the size of array : ";
cin>>size;
int *arr = new int[size];
inputArray(arr,size);
start = clock();
mergeSort(arr,0,size-1);
end = clock();
display_arr(arr,size);
cout<<"Time Taken by Merge Sort = "<<((double) (end-start)/CLOCKS_PER_SEC)*1000 <<" ms\n";
delete[] arr;
arr = NULL;
cout<<"MERGE SORT TIME COMPLEXITY\n";
cout<<"A_Size\tTime(ms)\n";
for(int i=1;i<=pow(10,6);)
{
size = i;
arr = new int[size];
RandArr(arr,size);
start = clock();
mergeSort(arr,0,size-1);
end = clock();
cout<<size<<"\t"<<((double) (end-start)/CLOCKS_PER_SEC)*1000 <<"\n";
delete[] arr;
arr = NULL;
i = i*10;
}
}
void mergeSort(int arr[],int s,int e)
{
if(s>=e)
{
return;
}
int m = (s+e)/2;
mergeSort(arr,s,m);
mergeSort(arr,m+1,e);
merge(arr,s,m,e);
//display_arr(arr,6);
}
void merge(int arr[],int s,int m,int e)
{
int new_arr[e-s+1];
int i=s,j=m+1,k=0;
while(i<=m && j<=e)
{
if(arr[i]<=arr[j])
{
new_arr[k++] = arr[i++];
}
if(arr[j]<arr[i])
{
new_arr[k++] = arr[j++];
}
}
while(i<=m)
{
new_arr[k++] = arr[i++];
}
while(j<=e)
{
new_arr[k++] = arr[j++];
}
for(int i=s,k=0;i<=e;)
{
arr[i++] = new_arr[k++];
}
}
void display_arr(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n";
}
void RandArr(int arr[],int n)
{
int upper = 100;
for(int i=0;i<n;i++)
{
arr[i] = rand()%upper;
}
}
void inputArray(int arr[],int n)
{
cout<<"Enter the elements of the Array : ";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
}