-
Notifications
You must be signed in to change notification settings - Fork 5
/
mergeSort.cpp
57 lines (54 loc) · 921 Bytes
/
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
#include<bits/stdc++.h>
using namespace std;
void merge(int *Arr, int start, int mid, int end) {
int temp[end - start + 1];
int i = start, j = mid+1, k = 0;
while(i <= mid && j <= end) {
if(Arr[i] <= Arr[j]) {
temp[k] = Arr[i];
k++;
i++;
}
else {
temp[k] = Arr[j];
k++;
j++;
}
}
while(i <= mid) {
temp[k] = Arr[i];
k++;
i++;
}
while(j <= end) {
temp[k] = Arr[j];
k += 1; j += 1;
}
for(i = start; i <= end; i += 1) {
Arr[i] = temp[i - start];
}
}
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 arr[100],n,i;
cout<<"enter the size and elements of array";
cin>>n;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
mergeSort(arr,0,n-1);
cout<<"sorted array:"<<endl;
for(i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
}