-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSA_35_Merge_sort.cpp
More file actions
56 lines (54 loc) · 1.21 KB
/
DSA_35_Merge_sort.cpp
File metadata and controls
56 lines (54 loc) · 1.21 KB
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
#include<iostream>
using namespace std;
void merge(int *arr,int s,int e){
int mid=s+(e-s)/2;
int len1=mid-s+1;
int len2=e-mid;
int *first=new int[len1];
int *second=new int[len2];
int mainarrayindex=s;
for(int i=0;i<len1;i++){
first[i]=arr[mainarrayindex++];
}
mainarrayindex=mid+1;
for(int i=0;i<len1;i++){
second[i]=arr[mainarrayindex++];
}
int index1=0;
int index2=0;
mainarrayindex=s;
while(index1<len1 && index2<len2){
if(first[index1]<second[index2]){
arr[mainarrayindex++]=first[index1++];
}
else{
arr[mainarrayindex++]=second[index2++];
}
}
while(index1<len1){
arr[mainarrayindex++]=first[index1++];
}
while(index2<len2){
arr[mainarrayindex++]=second[index2++];
}
}
void mergesort(int *arr,int s,int e){
if(s>=e){
return;
}
int mid=s+(e-s)/2;
mergesort(arr,s,mid);
mergesort(arr,mid+1,e);
merge(arr,s,e);
}
int main(){
int arr[7]={38,27,43,3,9,82,10};
int n=7;
mergesort(arr,0,n-1);
cout<<"Namastey Duniya \n"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}