-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.h
More file actions
73 lines (56 loc) · 1.18 KB
/
merge_sort.h
File metadata and controls
73 lines (56 loc) · 1.18 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
68
69
70
71
72
73
#ifndef _CLASS_MERGE_SORT_
#define _CLASS_MERGE_SORT_
#include "sort.h"
class merge_sort: public sort{
public:
explicit merge_sort(int num):sort(num){
cout<<"create merge_sort successfully"<<endl;
}
explicit merge_sort(const int *array, int num):sort(array, num){
cout<<"create merge_sort successfully"<<endl;
}
~merge_sort(){
cout<<"free merge_sort successfully, ";
}
void merge(int *a, int left, int mid, int right){
int length = right - left + 1;
int *tmp = new int[length];
int l = left;
int r = mid + 1;
int t = 0;
while(l <= mid && r <= right){
if (a[l] <= a[r]){
tmp[t++] = a[l++];
}else{
tmp[t++] = a[r++];
}
}
while(l <= mid){
tmp[t++] = a[l++];
}
while(r <= right){
tmp[t++] = a[r++];
}
memcpy(a+left, tmp, sizeof(int)*length);
delete[] tmp;
}
void sort_l2r(int *a, int left, int right){
int mid;
if (left < right){
mid = (left + right) / 2;
sort_l2r(a, left, mid);
sort_l2r(a, mid+1, right);
merge(a, left, mid, right);
}
}
void mergesort(){
sort_l2r(a_, 0, n_-1);
}
void print_a_(){
cout<<"merge sorted array: ";
for (int i = 0; i < n_; i++)
cout<<a_[i]<<" ";
cout<<endl;
}
};
#endif