归并排序C++

2023-12-27 11:24:48

?代码如下

// -- 归并排序
void Merge(RecType R[], int low, int mid, int high)
{
	RecType* R1;
	int i = low, j = mid + 1, k = 0; // i,j为两段起始下标 k是R1下标
	R1 = (RecType*)malloc((high - low + 1) * sizeof(RecType));
	while (i <= mid && j <= high)
		if (R[i].key <= R[j].key)  //放入R1
		{
			R1[k] = R[i];
			i++;
			k++;
		}
		else
		{
			R1[k] = R[j];
			j++;
			k++;
		}
	while (i <= mid)
	{
		R1[k] = R[i];
		i++;
		k++;
	}
	while (j <= high)
	{
		R1[k] = R[j];
		j++;
		k++;
	}
	for (k = 0, i = low; i <= high; k++, i++)
		R[i] = R1[k];
	free(R1);
}
//一趟归并
void MergePass(RecType R[], int length, int n)
{
	int i;
	for (i = 0; i + 2 * length - 1 < n; i = i + 2 * length)
	{
		Merge(R, i, i + length - 1, i + 2 * length - 1);
	}
	if (i + length - 1 < n - 1)
		Merge(R, i, i + length - 1, n - 1);
}
//二路归并
void MergeSort(RecType R[], int n)
{
	int length;
	for (length = 1; length < n; length = 2 * length)
	{
		MergePass(R, length, n);
	}
}
// 自顶向下
void MergeSortDC(RecType R[], int low, int high)
{
	int mid;
	if (low < high)
	{
		mid = (low + high) / 2;
		MergeSortDC(R, low, mid);
		MergeSortDC(R, mid + 1, high);
		Merge(R, low, mid, high);
	}
}
void MergeSort1(RecType R[], int n) //自顶向下
{
	MergeSortDC(R, 0, n - 1);
}

自顶向下的

// 自顶向下
void MergeSortDC(RecType R[], int low, int high)
{
?? ?int mid;
?? ?if (low < high)
?? ?{
?? ??? ?mid = (low + high) / 2;
?? ??? ?MergeSortDC(R, low, mid);
?? ??? ?MergeSortDC(R, mid + 1, high);
?? ??? ?Merge(R, low, mid, high);
?? ?}
}
void MergeSort1(RecType R[], int n) //自顶向下
{
?? ?MergeSortDC(R, 0, n - 1);
}

文章来源:https://blog.csdn.net/TXLTF/article/details/135201981
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。