forked from ZenanZha/btp500-f16
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.cpp
82 lines (74 loc) · 1.8 KB
/
merge.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
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "timer.h"
using namespace std;
void Merge(int arr[],int tmp[],int startA,int startB,int endB);
void MergeSort(int arr[],int tmp[],int start,int end){
//if the array is more than one element big
if(start<end){
int mid=(start+end)/2;
MergeSort(arr,tmp,start,mid);
MergeSort(arr,tmp,mid+1,end);
Merge(arr,tmp,start,mid+1,end);
}
}
/*function merges the two halfs of a sorted array together.
The arrays are defined from arr[startA]to arr[startB-1] and arr[startB]
to arr[endB]*/
void Merge(int arr[],int tmp[],int startA,int startB,int endB){
int aptr=startA;
int bptr=startB;
int idx=startA;
while(aptr < startB && bptr < endB+1){
if(arr[aptr] < arr[bptr]){
tmp[idx]=arr[aptr];
idx++;
aptr++;
}
else{
tmp[idx++]=arr[bptr];
bptr++;
}
}
//merge function only does one of the two following loops
while(aptr<startB){
tmp[idx]=arr[aptr];
idx++;
aptr++;
}
while(bptr < endB+1){
tmp[idx++]=arr[bptr];
bptr++;
}
//copy back into arr
for(int i=startA;i<=endB;i++){
arr[i]=tmp[i];
}
}
/*this is the wrapper function that "main" uses. The world see's this and
use this. The actual work is done by the other MergeSort() function*/
void MergeSort(int arr[],int size){
int* tmp=new int[size];
MergeSort(arr,tmp,0,size-1);
delete [] tmp;
}
int main(int argc, char* argv[]){
int size=atoi(argv[1]);
int *myarr=new int[size];
Timer stopwatch;
ofstream log("mergelog.txt");
for(int i=0;i<size;i++){
myarr[i]=rand();
// myarr[i]=i+1;
}
stopwatch.start();
MergeSort(myarr,size);
stopwatch.stop();
cout << stopwatch.currtime() << endl;
/* for(int i=0;i<size;i++){
log <<myarr[i]<< endl;
}*/
delete [] myarr;
return 0;
}