跟着两位大佬的步伐继续学算法,这次是归并排序,还是直接上代码。。。

代码

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
#include <iostream>

using namespace std;

void mergeArray(int* a, int first, int mid, int last, int* res) //将两个有序数列合并
{
int i = 0;
int left = first;
int right = mid + 1;

while(left <= mid && right <= last)
{
if(a[left] < a[right])
res[i++] = a[left++];
else
res[i++] = a[right++];
}

while(left <= mid)
res[i++] = a[left++];

while(right <= last)
res[i++] = a[right++];

for(int j = 0; j < i; j++) //将最终结果放到原数组里,删除临时数组res,减少new操作,节省时间
a[first+j] = res[j];
}

void mergeSort(int* a, int first, int last, int* res)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(a, first, mid, res); //数列左边递归分解,使其有序
mergeSort(a, mid+1, last, res); //右边
mergeArray(a, first, mid, last, res); //合并左右序列
// for(int i = 0; i < 10; i++)
// cout << a[i] << ' ';
// cout << endl;
}
}

int main()
{
int num;
cin >> num;

int* res = new int [num];
int* a = new int [num];
for(int i = 0; i < num; i++)
cin >> a[i];

mergeSort(a, 0, num-1, res);

for(int i = 0; i < num; i++)
cout << a[i] << ' ';
cout << endl;

delete [] a;
delete [] res;
return 0;
}