-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.cpp
60 lines (51 loc) · 1.23 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
#include<iostream>
using namespace std;
void merge(int *Arr, int start, int mid, int end) {
// create a temp array
int temp[end - start + 1];
// crawlers for both intervals and for temp
int i = start, j = mid+1, k = 0;
// traverse both arrays and in each iteration add smaller of both elements in temp
while(i <= mid && j <= end) {
if(Arr[i] <= Arr[j]) {
temp[k] = Arr[i];
k += 1; i += 1;
}
else {
temp[k] = Arr[j];
k += 1; j += 1;
}
}
// add elements left in the first interval
while(i <= mid) {
temp[k] = Arr[i];
k += 1; i += 1;
}
// add elements left in the second interval
while(j <= end) {
temp[k] = Arr[j];
k += 1; j += 1;
}
// copy temp to original interval
for(i = start; i <= end; i += 1) {
Arr[i] = temp[i - start];
}
}
// Arr is an array of integer type
// start and end are the starting and ending index of current interval of Arr
void mergeSort(int *Arr, int start, int end) {
if(start < end) {
int mid = (start + end) / 2;
mergeSort(Arr, start, mid);
mergeSort(Arr, mid+1, end);
merge(Arr, start, mid, end);
}
}
int main()
{
int A[]={9,48,25,65,14,5};
mergeSort(A,0,5);
for(int i=0;i<5;i++)
cout<<A[i]<<" ";
return 0;
}