排序算法:直接插入排序归并排序(递归与非递归实现)
Posted It‘s so simple
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序算法:直接插入排序归并排序(递归与非递归实现)相关的知识,希望对你有一定的参考价值。
目录
1. 直接插入排序
void InsertSort(vector<int>& iv)
for (int i = 0; i < iv.size() - 1; ++i)
int end = i;
int tmp = iv[end + 1];
while (end >= 0 && iv[end] > tmp)
iv[end + 1] = iv[end];
--end;
iv[end + 1] = tmp;
2.归并排序
2.1 递归
void _MergeSort(vector<int>& iv, int left, int right, vector<int>& tmp)
if (left >= right)
return;
int mid = left + ((right - left) >> 1);
_MergeSort(iv, left, mid, tmp);
_MergeSort(iv, mid + 1, right, tmp);
int begin1 = left;
int end1 = mid;
int begin2 = mid + 1;
int end2 = right;
int i = left;
while (begin1 <= end1 && begin2 <= end2)
if (iv[begin1] < iv[begin2])
tmp[i++] = iv[begin1++];
else
tmp[i++] = iv[begin2++];
while (begin1 <= end1)
tmp[i++] = iv[begin1++];
while (begin2 <= end2)
tmp[i++] = iv[begin2++];
int k = left;
while (k <= right)
iv[k] = tmp[k];
k++;
void MergeSort(vector<int>& iv)
vector<int> tmp(iv);
_MergeSort(iv, 0, iv.size() - 1, tmp);
2.2 非递归
void _MergeSortNOR(vector<int>& iv, int left, int right)
vector<int> tmp(iv.size());
int n = iv.size();
int gap = 1;
while (gap < n)
for (int i = 0; i < n; i += gap*2)
int begin1 = i;
int end1 = i + gap - 1;
int begin2 = i + gap;
int end2 = i + 2 * gap - 1;
if (begin2 >= n)
break;
if (end2 >= n)
end2 = n - 1;
int j = begin1;
while (begin1 <= end1 && begin2 <= end2)
if (iv[begin1] < iv[begin2])
tmp[j++] = iv[begin1++];
else
tmp[j++] = iv[begin2++];
while (begin1 <= end1)
tmp[j++] = iv[begin1++];
while (begin2 <= end2)
tmp[j++] = iv[begin2++];
int k = i;
while (k <= end2)
iv[k] = tmp[k];
k++;
gap *= 2;
以上是关于排序算法:直接插入排序归并排序(递归与非递归实现)的主要内容,如果未能解决你的问题,请参考以下文章