学习递归最开始就是斐波那契和归并排序。核心思想就是递归地把序列分成两部分,直到只剩一个元素。然后将每次划分的两部分再递归地合并起来,合并时候的顺序觉决定了排序的顺序还是逆序。
划分的过程可以看做是生成一颗叶子结点数为n的二叉树,这个过程的复杂度为lgn(树的高度)。而合并的过程是相当于将每层的节点数相加,复杂度为n*lgn。所以整体的复杂度为O(nlgn)。CLRS里给的复杂度分析方法是递归树(recurve tree),还不是特别理解,需要再研究。代码如下:
// mergeSort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
//合并
vector<int> merge(const vector<int> &v1, const vector<int> &v2)
{
vector<int> ans;
int size1 = v1.size();
int size2 = v2.size();
int size_min = size1 < size2 ? size1 : size2;
int i = 0, j = i;
while(i<size1&&j<size2)
{
if (v1[i] < v2[j])
{
ans.push_back(v1[i]);
++i;
}
else
{
ans.push_back(v2[j]);
++j;
}
}
for (int k = i; k < size1; k++)
ans.push_back(v1[k]);
for (int l = j; l < size2; l++)
ans.push_back(v2[l]);
return ans;
}
//unit test
void test_merge()
{
cout << "Test merge():" << endl;
vector<int> v1 = { 1,2,4,7,9 };
vector<int> v2 = { 3,4,7,9,76 };
auto ans = merge(v1, v2);
for (auto i : ans)
cout << i << endl;
}
//排序
void mergeSort(vector<int>& v,int n)
{
if (n == 1)
return;
else
{
vector<int> first_half(v.cbegin(), v.cbegin() + n / 2);
vector<int> second_half(v.cbegin() + n / 2 , v.cend());
mergeSort(first_half, first_half.size());
mergeSort(second_half, second_half.size());
v = merge(first_half, second_half);
}
}
int main()
{
//test_merge();
vector<int> a = { 8,2,4,9,3,6 };
mergeSort(a, a.size());
for (auto i : a)
cout << i << endl;
system("pause");
return 0;
}
运行结果: