-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.cpp
85 lines (65 loc) · 1.45 KB
/
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
#include <iostream>
#include <array>
using namespace std;
void merge(int arr[],int start,int mid,int last){
int left = mid-start+1;
int right =last - mid ;
int leftArray[left];
int rightArray[right];
int i;
int j;
int k;
//copy contents
for (i=0;i<left;i++)leftArray[i]=arr[start+i];
for (j=0;j<right;j++)rightArray[j]=arr[mid+1+j];
i =0 ;
j =0 ;
k = start ;
while(i<left && j<right){
if(leftArray[i]<= rightArray[j]){
arr[k] = leftArray[i];
i++;
}
else{
arr[k] = rightArray[j];
j++;
}
k++;
}
while(i<left){
arr[k] = leftArray[i];
i++;
k++;
}
while(i<right){
arr[k] = rightArray[j];
j++;
k++;
}
}
void display(int arr[]) {
for(int i = 0; i <6; i++)
cout << arr[i] << " ";
cout << endl;
}
void divide(int arr[],int start,int last){
if(start < last){
int mid= (start + last)/2;
divide(arr,start,mid);
divide(arr,mid+1,last);
merge(arr,start,mid,last);
}
}
int main(){
int size;
cout<<"Enter the size of the Array that is to be sorted: "; cin>>size;
int Hello[size],i;
cout<<"Enter the elements of the array one by one:n";
for(i=0; i<size; i++) cin>>Hello[i];
divide(Hello, 0, size - 1);
cout<<"The Sorted List isn";
for(i=0; i<size; i++)
{
cout<<Hello[i]<<" ";
}
}