#include<iostream>
using namespace std;
#define SIZE 1024
/*1、如果可以申请辅助空间,那么从前从后倒是没什么所谓吧,这就像是归并的一次归并了。*/
void Merge_1(int *arr,int lenarr,int *brr,int lenbrr)
{
if(brr == NULL)//如果brr为空,则没有合并的必要
return;
if(arr == NULL) //如果arr为空,直接把brr赋值给arr即可
{
for(int i=0;i<lenbrr;++i)
{
arr[i] = brr[i];
}
}
int *tmp = new int[lenarr+lenbrr];
int index = 0;
int low1 = 0,low2 = 0;
while(low1< lenarr && low2 < lenbrr)
{
while (arr[low1] < brr[low2] && low1 < lenarr)
{
tmp[index ++] = arr[low1 ++];
}
while (arr[low1] > brr[low2] && low2 < lenbrr)
{
tmp[index ++] = brr[low2++];
}
}
while(low1 < lenarr ) //如果串1没完,则继续走串1
{
tmp[index ++] = arr[low1 ++];
}
while(low2 < lenbrr) //如果串2没完,则继续走串2
{
tmp[index ++] = brr[low2++];
}
for(int i=0;i<lenarr+lenbrr;++i)
{
arr[i] = tmp[i];
}
delete[] tmp;
}
/*2、如果不申请额外空间,则就要注意,从后往前走了*/
void Merge_2(int *arr,int lenarr,int *brr,int lenbrr)
{
int lennew = lenarr + lenbrr -1;
int high1 = lenarr -1 ;
int high2 = lenbrr -1;
while(high1>=0 && high2>=0)
{
while(arr[high1] > brr[high2] && high1 >= 0)
{
arr[lennew--] = arr[high1 --];
}
while(arr[high1] < brr[high2] && high2 >= 0)
{
arr[lennew--] = brr[high2 --];
}
}
while(high1 >=0 ) //如果串1没完,则继续走串1
{
arr[lennew--] = arr[high1 --];
}
while(high2 >= 0 ) //如果串2没完,则继续走串2
{
arr[lennew--] = brr[high2 --];
}
}
int main()
{
int arr[SIZE] = {1,5,7,9,11};
int brr[SIZE] = {2,3,4,6,8,10,12,24};
//Merge_1(arr,5,brr,8);
Merge_2(arr,5,brr,8);
for(int i=0;i<13;++i)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
有序数组的合并
最新推荐文章于 2021-10-19 17:46:47 发布