合并排序数组II

合并两个排序的整数数组A和B变成一个新的数组。
 注意事项
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
样例
给出 A = [1, 2, 3, empty, empty], B = [4, 5]

合并之后 A 将变成 [1,2,3,4,5]


import java.util.Scanner;

/**
 * 合并两个排序的整数数组A和B变成一个新的数组。
 注意事项
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
样例
给出 A = [1, 2, 3, empty, empty], B = [4, 5]
合并之后 A 将变成 [1,2,3,4,5]
 * 
 * @author Dell
 *
 */
public class Test64 {
  public static void mergeSortedArray(int[] A, int m, int[] B, int n)
  {
	 int[] result=new int[m+n];
	 
	 int i=0;
	 int j=0;
	 int k=0;
	 while(i<m&&j<n)
	 {
		 if(A[i]<B[j])
		 {
			 result[k++]=A[i];
			 i++;
		 }
		 else {
			 
			 result[k++]=B[j];
			 j++;
		 } 
	 }
	if(i<m)
	{
		for(int z=i;z<m;z++)
		{
			result[k++]=A[z];
		}
	}
	if(j<n)
	{
		for(int z=j;z<n;z++)
		{
			result[k++]=B[z];
		}
	}
	for(int b=0;b<m+n;b++)
	{
		
		A[b]=result[b];
	}
	 
  }
	public static void main(String[] args) {
		 Scanner sc=new Scanner(System.in);
          int m=sc.nextInt();
          int n=sc.nextInt();
          int[] A=new int[m+n];
          int[] B=new int[n];
          for(int i=0;i<m;i++)
          {
        	  A[i]=sc.nextInt();
          }
		  for(int i=0;i<n;i++)
		  {
			  B[i]=sc.nextInt();
		  }
		  mergeSortedArray(A,m,B,n); 
		  for(int i=0;i<m+n;i++)
		  {
		  System.out.print(A[i]+" ");
		  }
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值