归并排序

一、归并排序-递归

1. 图解思路

if (left >= right)
{
return;
}

2. 代码

//归并排序
void _MergeSort(int* a, int left, int right, int* tmp)
{
if (left >= right)
{
return;
}

int mid = (left + right) / 2;
//左右递归，
_MergeSort(a, left, mid, tmp);
_MergeSort(a, 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 (a[begin1] > a[begin2])
{
tmp[i++] = a[begin2++];
}
else
{
tmp[i++] = a[begin1++];

}
}

while (begin1 <= end1)
{
tmp[i++] = a[begin1++];
}

while (begin2 <= end2)
{
tmp[i++] = a[begin2++];
}

//tmp数组拷贝回a
for (int j = left; j <= right; ++j)
{
a[j] = tmp[j];
}
}

void MergeSort(int* a, int n)
{
int* tmp = (int*)malloc(sizeof(int) * n);
if (tmp == NULL)
{
printf("malloc fail");
exit(-1);
}

_MergeSort(a, 0, n - 1, tmp);

free(tmp);
tmp = NULL;

}

二、归并排序-非递归

1. 图解思路

• 情况1：begin2 和 end2 都越界

• 情况2：end2 越界

2. 代码

//归并非递归
void MergeSortNonR(int* a, int n)
{
int* tmp = (int*)malloc(sizeof(int) * n);
if (tmp == NULL)
{
printf("malloc fail");
exit(-1);
}

int gap = 1;
while (gap < n)
{
for (int i = 0; i < n; i += 2 * gap)
{
int begin1 = i;
int end1 = i + gap - 1;
int begin2 = i + gap;
int end2 = i + 2 * gap - 1;
int index = i;

if (end1 >= n || begin2 >= n)
{
break;
}

if (end2 >= n)
{
end2 = n - 1;
}

while (begin1 <= end1 && begin2 <= end2)
{
if (a[begin1] < a[begin2])
{
tmp[index++] = a[begin1++];
}
else
{
tmp[index++] = a[begin2++];

}
}

while (begin1 <= end1)
{
tmp[index++] = a[begin1++];
}

while (begin2 <= end2)
{
tmp[index++] = a[begin2++];
}

//tmp数组拷贝回a
for (int j = i; j <= end2; ++j)
{
a[j] = tmp[j];
}

}

gap *= 2;

}

free(tmp);
tmp = NULL;

}

vs2019可能会出现

THE END