merge

Merge Sort

归并排序是稳定排序算法,时间复杂度O(nlogn),空间复杂度O(n),如果采用原地归并,空间复杂度为O(1).

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
void (int* arr, int n){
MergeSort(arr, 0, n - 1);
}

void (int* arr, int low, int high){
if(low < high){
int mid = low + (high - low) / 2;
MergeSort(arr, low, mid);
MergeSort(arr, mid + 1, high);
Merge(arr, low, mid + 1, high);
}
}

void Merge(int* arr, int left_pos, int right_pos, int right_end) {
int left_end = right_pos - 1;
int tmp_pos = 0;
int num_elements = right_end - left_pos + 1;
int* _arr = new int[num_elements];
while (left_pos <= left_end && right_pos <= right_end) {
if (arr[left_pos] <= arr[right_pos]) {
_arr[tmp_pos++] = move(arr[left_pos++]);
} else {
_arr[tmp_pos++] = move(arr[right_pos++]);
}
}
while (left_pos <= left_end) {
_arr[tmp_pos++] = move(arr[left_pos++]);
}
while (right_pos <= right_end) {
_arr[tmp_pos++] = move(arr[right_pos++]);
}
for (int i = 0; i < num_elements; ++i, --right_end) {
arr[right_end] = move(_arr[num_elements - i - 1]);
}
delete[] _arr;
}