-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprg27.cpp
More file actions
67 lines (67 loc) · 1.01 KB
/
Copy pathprg27.cpp
File metadata and controls
67 lines (67 loc) · 1.01 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
63
64
65
66
67
//merge sort
#include<iostream>
using namespace std;
class mergesort{
public: void msort(int arr[20],int low,int mid,int high);
void merge(int arr[20],int low,int high);
};
void mergesort::msort(int arr[20],int low,int mid,int high)
{
int temp[high-low+1];
int i=low;
int j,k;
j=mid+1;
k=0;
while(i<=mid && j<=high)
{
if(arr[i]<arr[j]){
temp[k]=arr[i];
i++;
k++;
}
else{
temp[k]=arr[j];
j++;
k++;
}
}
while(i<=mid){
temp[k]=arr[i];
i++;
k++;
}
while(j<=high){
temp[k]=arr[j];
j++;
k++;
}
for(i=low;i<=high;i++){
arr[i]=temp[i-low];
}
}
void mergesort::merge(int arr[20],int low,int high)
{
int mid;
if(low<high)
{
mid=((low+high)/2);
merge(arr,low,mid);
merge(arr,mid+1,high);
msort(arr,low,mid,high);
}
}
main()
{
mergesort m;
int arr[20];
int n,i;
cout<<"Enter the number of elements: ";
cin>>n;
cout<<"Enter "<<n<<" elements: ";
for(i=0;i<n;i++)
cin>>arr[i];
m.merge(arr,0,n-1);
cout<<"\nAfter sorting";
for(i=0;i<n;i++)
cout<<arr[i]<<"\n";
}