【代码分享】

//归并排序的递归函数
void D_MereSort(int a[], int left, int right, int* tmp)
{
//left和right分别为递归区间的左右端点的下标
//把要归并的两边的区间递归到各只有1个元素就停
if (left >= right)
return;
//mid为递归区间中间下标
int mid = (left + right) / 2;

//递归
D_MereSort(a, left, mid, tmp);
D_MereSort(a, mid+1, right, tmp);

//定义begin和end接受left和right
//防止left和right改变,导致出错
int begin1 = left, end1 = mid;
int begin2 = mid+1, end2 = right;
//i必须有且值只能是  左侧区间的左端点  即left
int i = left;

//归并算法
while (begin1 <= end1 && begin2 <=end2)
{
	if (a[begin1] < a[begin2])
	{
		tmp[i++] = a[begin1++];
	}
	else
	{
		tmp[i++] = a[begin2++];
	}
}
while (begin1 <= end1)
{
	tmp[i++] = a[begin1++];
}
while (begin2 <= end2)
{
	tmp[i++] = a[begin2++];
}
int j = left;
//将归并好的放回要排序的数组
for (; j<=right; j++)
	a[j] = tmp[j];

}

//归并排序(递归)
void MergeSort1(int a[], int n)
{
//创建临时空间,方便归并
int* tmp = (int*)malloc(sizeof(int) * n);
//用于递归的函数
D_MereSort(a, 0, n - 1, tmp);
//释放申请空间
free(tmp);
}

//归并排序的非递归实现
void MergeSort2(int a[], int n)
{
//申请空间
int* tmp = (int*)malloc(sizeof(int) * n);
//gap表示归并的左右区间的元素个数
int gap = 1;
int j = 0;
while (gap < n)//gap不能等于数组的总元素个数
{
for (j = 0; j < n; j += 2 * gap)
{
int i = j; //防止循环变量改变,影响循环

		int begin1 = i, end1 = i + gap - 1;
		int begin2 = i + gap, end2 = i + 2 * gap - 1;

		if (begin2 >= n)//右区间  左端点越界,就直接可以结束
			break;
		if (end2 >= n)//右区间  右端点越界,就将它改为n-1
			end2 = n - 1;
		//归并
		while (begin1 <= end1 && begin2 <= end2)
		{
			if (a[begin1] < a[begin2])
			{
				tmp[i++] = a[begin1++];
			}
			else
			{
				tmp[i++] = a[begin2++];
			}
		}
		while (begin1 <= end1)
		{
			tmp[i++] = a[begin1++];
		}
		while (begin2 <= end2)
		{
			tmp[i++] = a[begin2++];
		}
	}
	int z = 0;
	//归并结束后,将归并完成的拷贝回去
    //为下次循环的归并做准备
	for (z = 0; z < n; z++)
		a[z] = tmp[z];
	
	gap *= 2;
}

}

你可能感兴趣的:(c语言)