合并排序非递归法与递归法
书上的算法,进行了注释,可直接运行,递归的思想是看下面整张图片,非递归的思想仅看红线圈的即可,有错误请留言。
非递归法
#include<iostream>
using namespace std;
void merge(int c[],int d[],int l,int m, int r) { //合并c[l:m]和c[m+1:r]到d[1:r]
int i = l, j = m + 1, k = l;
while ((i <= m) && (j <= r))
{
if (c[i] <= c[j]) {
d[k++] = c[i++];
}
else {
d[k++] = c[j++];
}
}
if (i > m)
{
for (int q = j; q <= r; q++) {
d[k++] = c[q];
}
}
else
{
for (int q = i; q <= m; q++)
{
d[k++] = c[q];
}
}
}
void mergepass(int x[], int y[], int s, int n) { //合并大小为s的相邻数组
int i = 0;
while (i < n - 2 * s) 合并大小为s的相邻2段子数组
{
merge(x, y, i, i + s - 1, i + 2 * s - 1);
i = i + 2 * s;
}
if (i+s<n) //剩下的元素个数小于2s但是大于s ,意味着还能归并,只是两者长度不同
{
merge(x, y, i, i + s - 1, n - 1);
}
else //剩下的元素个数小于等于s个,只剩一段了就不用排了,放在后面就行了【这一步还有个作用就是在最后将b数组全部复制给a(不明白意思的可以先不看这句)】
{
for (int j = i; j <= n-1; j++)
{
y[j] = x[j];
}
}
}
void mergesort(int a[], int n) {
int* b = new int[n]; //创建辅助数组b
int s = 1;
while (s < n)
{
mergepass(a, b, s, n); //合并到数组b
s += s;
mergepass(b,a, s, n); //合并到数组a
s += s;
}
}
int main() {
int a[] = {1,5,9,4,6,8,7};
mergesort(a, 7);
for (int i = 0; i < 7; i++) {
cout << a[i] << endl;
}
}
递归法
#include<iostream>
using namespace std;
void Merge(int array[], int left, int mid, int right) {
int *array2 = new int[right - left +1]; //创建辅助数组
int begin1 = left, end1 = mid;
int begin2 = mid + 1, end2 = right;
int k = 0; //记录辅助数组下标位置
while ((begin1 <= end1) && (begin2 <= end2))
{
if (array[begin1] < array[begin2])
{
array2[k++] = array[begin1++];
}
else
{
array2[k++] = array[begin2++];
}
}
while (begin1 <= end1)
{
array2[k++] = array[begin1++];
}
while (begin2 <= end2)
{
array2[k++] = array[begin2++];
}
for (int i = 0; i < (right - left + 1); i++) //将排好序的辅助数组中的内容复制到原数组
{
array[left+i] = array2[i];
}
delete array2; //删除创建辅助数组时申请的空间
}
void MergeSort(int a[], int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
MergeSort(a, left, mid);
MergeSort(a, mid + 1, right);
Merge(a, left, mid, right);
}
}
int main() {
int a[] = {5,8,3,4,9,7,1,2,6 };
int n = 8;
MergeSort(a, 0, n);
cout << "合并后的排序为:" << endl;
for (int i = 0; i <= n; i++) {
cout << a[i] <<endl;
}
}