归并排序用到了很重要的递归思想,下面给大家贴上本人归并排序的过程和递归步骤,帮助大家更好的理解归并排序
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int temp[20] = { 0 };
int merge(int source[],int L, int mid_index ,int R)
{
printf("之前的temp
");
for (int i = 0; i <= R; i++)
{
printf("%d ", temp[i]);
}
int i = L;
int j = mid_index + 1;
int k = L;
while (i <= mid_index && j <= R)
{
temp[k++] = source[i] < source[j] ? source[i++] : source[j++];
}
while (i <= mid_index)
{
temp[k++] = source[i++];
}
while (j <= R)
{
temp[k++] = source[j++];
}
printf("
之后的temp
");
for (int i = L; i <=R; i++)//这一步是至关重要的,很多初学归并排序的同学忽略了这一步,以为最后打印temp就行了
{
printf("%d ", temp[i]);
source[i] = temp[i];
//从下面的解析过程可以看出,每次调用merge完后,必须把已经排好序的数赋给原来的source,不然下次还是和没有排序过的数比较,就无法实现递归效果
}
printf("
");
}
int merge_process(int source[] , int L, int R)
{
if (L < R)
{
int mid_intex;
mid_intex = L + (R - L) / 2;
merge_process(source, L, mid_intex);
merge_process(source, mid_intex + 1, R);
merge(source, L, mid_intex, R);
}
}
int main()
{
int source[] = {80,30,60,40,20,10,50,70,15};
int len;
len = sizeof(source) / sizeof(int);
merge_process(source, 0, len -1 );
}
下面是解析过程,能看懂执行过程是g1->g2->g3->g4->g3->g2->g5->g2.....问题就不大了
g5:3 4 mid = 3 merge_progress(, ,3,3) merge_progress(, ,4,4) merge(334) temp(30,60,80,20,40)
g4:0 1 mid = 0 merge_progress(, ,0,0) merge_progress(, ,1,1) ,merge(001) temp(30,80)
g3:0 2 mid = 1 merge_progress(, ,0,1) g4 merge_progress(, ,2,2),merge(012) temp(30,60,80)
g2:0 4 mid = 2 merge_progress(, ,0,2) g3 merge_progress(, ,3,4) g5, merge(024)temp()
g1:0 7 mid= 4 merge_progress(, ,0,4) g2
首先执行g1,到merge_progress(, ,0,4)跳到g2
g2执行到merge_progress(, ,0,2)跳到g3
g3执行到 merge_progress(, ,0,1)跳到g4
g4执行到merge_progress(, ,0,0) 因为L==R,返回继续执行merge_progress(, ,1,1),同理返回执行
merge(001),得出temp(30,80)同时把temp排好序的值赋给source,返回g3
g3继续执行merge_progress(, ,2,2),因为L==R,返回执行merge(012),得出 temp(30,60,80),同时把temp排好序的值赋给source,返回g2,继续执行剩下的函数,依次归并