forked from Andyy-18/CPP-BASICS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathR_mergesort.cpp
93 lines (75 loc) · 1.58 KB
/
R_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
83
84
85
86
87
88
89
90
91
92
93
#include<bits/stdc++.h>
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 k=s;
for(int i=0;i<len1;i++){
first[i]=arr[k++];
}
k=mid+1;
for(int i=0;i<len2;i++){
second[i]=arr[k++];
}
//merge
int i=0,j=0;
k=s;
while(i<len1 && j<len2){
if(first[i]<second[j]){
arr[k++]=first[i++];
// k++;
// i++;
}
else{
arr[k++]=second[j++];
// k++;
// j++;
}
}
// agar ek array avi vi bacha ho to uska value arr3 mai copy kar do
while(i<len1){
arr[k++]=first[i++];
// k++;
// i++;
}
while(j<len2){
arr[k++]=second[j++];
// k++;
// j++;
}
delete [] first;
delete [] second;
}
void mergesort(int *arr,int s,int e){
//base case
if(s>=e){
return;
}
int mid=s+(e-s)/2;
//sorting left part
mergesort(arr,s,mid);
//sorting right part
mergesort(arr,mid+1,e);
//merge
merge(arr,s,e);
}
int main()
{
int n;
cout<<"Enter the size : "<<endl;
cin>>n;
int arr[n];
cout<<"Enter your numbers : "<<endl;
for(int i = 0; i < n; i++){
cin>>arr[i];
}
mergesort(arr,0,n-1);
cout<<"sorted array: ";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}