-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
55 lines (52 loc) · 1.35 KB
/
MergeSort.cpp
File metadata and controls
55 lines (52 loc) · 1.35 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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int* joinSorted(int* a,int sa,int* b,int sb){
int arr[sa+sb];
int index_a=0,index_b=0,i=0;
while(1){
if(index_a==sa && index_b==sb)
break;
if(index_a==sa){
arr[i++]=b[index_b++];
}
else if(index_b==sb){
arr[i++]=a[index_a++];
}
else{
if(a[index_a]>b[index_b]){
arr[i++]=b[index_b++];
}
else
arr[i++]=a[index_a++];
}
}
for(int i=0;i<sa+sb;i++)
a[i]=arr[i];
return a;
}
int* MergeSort(int* arr,int size){
if(size <= 1)
return arr;
int lsize = size/2;
int* LeftPart = MergeSort(arr,lsize);
int* RightSize = MergeSort(arr+lsize,size-lsize);
return joinSorted(LeftPart,lsize,RightSize,size-lsize);
}
int main(){
srand(time(0));
int n = 10+rand()%31; //size between 10 to 30
int* arr = new int[n];
cout<<"array before merge sort : "<<endl;
for(int i=0;i<n;i++){
arr[i] = rand()%41;//a number between 0 to 40
cout<<arr[i]<<' ';
}cout<<endl;
MergeSort(arr,n);
cout<<"array after merge sort : "<<endl;
for(int i=0;i<n;i++)
cout<<arr[i]<<' ';
cout<<endl;
return 0;
}