forked from abhijithshaji17/cpp-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path36.cpp
More file actions
62 lines (62 loc) · 1.26 KB
/
Copy path36.cpp
File metadata and controls
62 lines (62 loc) · 1.26 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
57
58
59
60
61
62
// Merge sort - recursive approach
#include<iostream>
using namespace std;
void merge(int a[], int lb, int mid, int ub){
int temp[20],i,j,k;
i = lb; j = mid + 1; k = lb;
while(i<=mid && j<=ub){
if(a[i]<=a[j]){
temp[k] = a[i];
i++;
}else{
temp[k] = a[j];
j++;
}
k++;
}if(i>mid){
while(j<=ub){
temp[k] = a[j];
j++;k++;
}
}else{
while(i<=mid){
temp[k] = a[i];
i++;k++;
}
}
for(i=lb;i<=ub;i++){
a[i] = temp[i];
}
}
void mergesort(int a[], int lb, int ub){
if(lb<ub){
int mid = (lb+ub)/2;
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
int main(){
int a[20],i,lb,ub;
cout<<"Enter the lower and upper bounds of array: ";
cin>>lb>>ub;
cout<<"Enter elements:\n";
for(i=lb;i<ub;i++){
cout<<"Element "<<i+1<<": ";
cin>>a[i];
}
cout<<"\nUnsorted Array:\n";
cout<<"[";
for(i=lb;i<ub;i++){
cout<<" "<<a[i];
}
cout<<"]\n";
mergesort(a,lb,ub);
cout<<"\nSorted Array:\n";
cout<<"[";
for(i=lb;i<ub;i++){
cout<<" "<<a[i];
}
cout<<"]\n";
return 0;
}