一、归并排序简介
将两个的有序数列合并成一个有序数列,我们称之为"归并"。
归并排序(Merge Sort)就是利用归并思想对数列进行排序。根据具体的实现,归并排序包括"从上往下"和"从下往上"2种方式。我们在此处实现“从上往下”的归并排序。
从上往下的归并排序基本包括3步:
① 分解 -- 将当前区间一分为二,即求分裂点 mid = (low + high)/2;
② 求解 -- 递归地对两个子区间a[low...mid] 和 a[mid+1...high]进行归并排序。递归的终结条件是子区间长度为1。
③ 合并 -- 将已排序的两个子区间a[low...mid]和 a[mid+1...high]归并为一个有序的区间a[low...high]。
二、归并排序的时间复杂度和稳定性
归并排序时间复杂度
归并排序的时间复杂度是O(N*lgN)。
假设被排序的数列中有N个数。遍历一趟的时间复杂度是O(N),需要遍历多少次呢?
归并排序的形式就是一棵二叉树,它需要遍历的次数就是二叉树的深度,而根据完全二叉树的可以得出它的时间复杂度是O(N*lgN)。
归并排序稳定性
归并排序是稳定的算法,它满足稳定算法的定义。
算法稳定性 -- 假设在数列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;并且排序之后,a[i]仍然在a[j]前面。则这个排序算法是稳定的!
三、C++代码实现
1.实现代码
//Sort.h
#include<vector>
using namespace std;
template <typename T>
bool lessthan(const T &a, const T &b)
{
return a < b;
}
template <typename T>
void exch(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T>
void show(const vector<T> &a)
{
for (auto tmp : a)
cout << tmp<<" ";
}
template <typename T>
bool isSorted(const vector<T> &a)
{
int cnt = a.size();
for (int i = 0; i < cnt-1; i++)
{
if (a[i] > a[i + 1])
return false;
}
return true;
}
template <typename T>
void read(vector<T> &v, const string s)
{
ifstream data(s); //待读取文件的目录
string line;
while (getline(data, line)) {
stringstream ss; //输入流
ss << line; //向流中传值
if (!ss.eof()) {
int temp;
while (ss >> temp) //提取int数据
v.push_back(temp); //保存到vector
}
}
}
#pragma region MergeSort
template <typename T>
T* aux;
template <typename T>
void merge(vector<T> &a, int lo, int mid, int hi)
{
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++)
aux<T>[k] = a[k];
for (int k = lo; k <= hi; k++)
{
if (i > mid) a[k] = a[j++];
else if (j > hi) a[k] = a[i++];
else if (lessthan(a[i], a[j])) a[k] = a[i++];
else a[k] = a[j++];
}
}
template <typename T>
void MSort(vector<T> &a, int lo, int hi)
{
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
MSort(a, lo, mid);
MSort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
template <typename T>
void MergeSort(vector<T> &a)
{
aux<T> = new T[a.size()];
MSort(a, 0, a.size() - 1);
}
#pragma endregion
2.用例代码
#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<string>
#include<vector>
#include<time.h>
#include"Sort.h"
using namespace std;
int main()
{
clock_t start, finish;
double time = 0; // CLOCKS_PER_SEC;
vector<int> vec;
read(vec, "4Kints.txt");
cout << vec.size() << endl;
for (int i = 0; i < 10; i++)
{
start = clock(); //测试程序段花费的时间
//SelectionSort(vec);
//InsertionSort(vec);
//ShellSort(vec);
MergeSort(vec);
//QuickSort(vec);
finish = clock();
time += (double)(finish - start);
cout << isSorted(vec) << endl;
random_shuffle(vec.begin(), vec.end());
}
cout << "运行时间是" << time << endl;
system("pause");
}