Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fcb6e0b

Browse files
Create merge-sort.cpp
1 parent 2854a11 commit fcb6e0b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎Sorting/Merge Sort/merge-sort.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
#define ll long long int
4+
#define loop(i,N) for(int i=0;i<N;i++)
5+
#define loop_(i,N) for(int i=1;i<=N;i++)
6+
7+
vector <int> ar;
8+
9+
void merge(int low,int mid,int high){
10+
int l1=mid-low+1;
11+
int l2=high-mid;
12+
int aux1[l1],aux2[l2]; // two auxillary arrays that would contain the two sorted lists
13+
loop(i,l1)
14+
aux1[i]=ar[low+i];
15+
loop(i,l2)
16+
aux2[i]=ar[mid+1+i];
17+
int i=0,j=0;
18+
while(i<l1 and j<l2){
19+
if(aux1[i]<aux2[j])
20+
ar[low++]=aux1[i++];
21+
else
22+
ar[low++]=aux2[j++];
23+
}
24+
while(i<l1){ // simply merge the remaining , if any
25+
ar[low++]=aux1[i++];
26+
}
27+
while(j<l2){ // simply merge the remaining, if any
28+
ar[low++]=aux2[j++];
29+
}
30+
}
31+
32+
void mergeSort(int low,int high){
33+
if(low<high){
34+
int mid=(low+high)/2; // or a fancy way to avoid integer overflow for large array sizes
35+
mergeSort(low,mid);
36+
mergeSort(mid+1,high);
37+
merge(low,mid,high);
38+
}
39+
}
40+
41+
int main(){
42+
int n,num;
43+
cin>>n;
44+
loop(i,n) cin>>num, ar.push_back(num);
45+
mergeSort(0,n-1);
46+
loop(i,n) cout<<ar[i]<<" ";
47+
cout<<endl;
48+
return 0;
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /