拼接两个不同长度的有序数组

拼接两个不同长度的有序数组

数组A的长度为m+n,其中有m个数,数组B的程度为n,其中有n个数。
数组A和数组B皆为有序数组(从小到大排列)。

#include
#include
#include

void Mer_Seq(int* target, const int* Basic, int m, int n)
{
     
	assert(Basic != nullptr && m > 0 && n > 0);
	int i = m - 1;
	int j = n - 1;
	int k = m + n - 1;
	while (k >= 0)
	{
     
		if (target[i] > Basic[j])
		{
     
			target[k] = target[i];
			--i;
		}
		else
		{
     
			target[k] = Basic[j];
			--j;
		}
		--k;
	}
}

int main()
{
     
	const int m = 5;
	const int n = 10;
	int ar[m + n] = {
      12,34,56,78,90 };
	int br[n] = {
      2,3,4,5,56,67,78,89,90,100 };

	Mer_Seq(ar, br, m, n);
	for (int i = 0; i < m + n; ++i)
	{
     
		printf("%d ", ar[i]);
	}
	return 0;
}

从数组A最后一位开始赋值,依次判断两个数组最后一位数,较大的赋值在最后。

有序数组合并(其它方法)

1、先将数组B的数字都拼接在数组A后面,然后再统一排序。
2、创建一个临时数组C,数组A和数组B从最小的开始依次赋值进数组C,再用数组C覆盖数组A。

你可能感兴趣的:(C语言,笔记,c语言)