-
Notifications
You must be signed in to change notification settings - Fork 5
/
MergeSort.cpp
82 lines (61 loc) · 1.31 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
#include <iostream>
using namespace std;
void merge(int arr[],int s , int e)
{
int mid = (s+e)/2;
int i = s;
int j = mid+1;
int k = s;
/* create temp arrays */
int temp[100];
while(i <= mid && j <= e)
{
// If the first value of left array is less than first value of right value
if(arr[i]<arr[j])
{
temp[k++] = arr[i++]; // Do this
}
else
{
temp[k++] = arr[j++]; // Else do this
}
}
// To copy the remaining number after comparing both the arrays and exhausting(Completing) one of them
while(i<=mid)
{
temp[k++] = arr[i++];
}
while(j<=e)
{
temp[k++] = arr[j++];
}
for(i=s ; i<=e ; i++ )
{
/* Copy data to temp array to our array */
arr[i] = temp [i];
}
}
void mergeSort(int arr[], int s , int e)
{
if(s>=e)
{
return;
}
// Same as (s+e)/2
int mid = s+(e-s)/2;
mergeSort(arr,s,mid);
mergeSort(arr,mid+1,e);
merge(arr,s,e);
}
int main(){
int arr[] = {2,4,6,3,3,6,2,1};
int size = sizeof(arr)/sizeof(arr[1]);
int start = 0;
int end = size;
mergeSort(arr,start,end-1);
for(int i= 0 ; i<size ; i++)
{
cout<<arr[i];
}
return 0;
}