将两个有序数列组合成一个有序数列

时间:2021-05-13 09:52:11

想法:1.测量序列长度;

            2.建堆存储新序列

            3.从小序列处开始进行插入排序


#include"iostream"

using namespace std;

int* sort(int *s1,int *s2,int len1,int len2)
{
	int *temp = (int*)malloc(sizeof(int)*(len1+len2));
	int i;
	for(i=0;i<len1;i++)
	{
		temp[i] = s1[i];
	}
	for(int j=0;j<len2;i++,j++)
	{
		temp[i] = s2[j];
	}

	for(int i=len1,j=0;j<len2;i++,j++)
	{
		int sw = temp[i];
		for(int k=i;k>0;k--)
		{
			if(temp[k]<temp[k-1])
			{
				temp[k] = temp[k-1];
				temp[k-1] = sw;
			}
		}
	}
	return temp;
}

void mainxlzh()
{
	int s1[5] = {11,12,13,45,66};
	int s2[5] = {10,14,20,55,71};
	int len1 = sizeof(s1)/sizeof(*s1);
	int len2 = sizeof(s2)/sizeof(*s2);
	int *s = NULL;
	s = sort(s1,s2,len1,len2);

	for(int i=0;i<(len1+len2);i++)
	{
		cout<<s[i]<<" ";
	}
	free(s);
	s = NULL;
	system("pause");
}