therrontelford

Sorted Arrays Merged

Jan 28th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1.  
  2. public class MergedArrays {
  3.  
  4.     public static void main(String[] args) {
  5.         int[] array1={2,4,5,6,7};
  6.         int[] array2={1,3,8,9,10};
  7.         int[] array3=new int[array1.length+ array2.length];
  8.         array3= merge(array1, array2);
  9.        
  10.         for (int e: array3)
  11.             System.out.print(e+ " ");
  12.        
  13.     }
  14.    
  15.     public static int[] merge(int[] arr1, int[] arr2){
  16.         int counter=0;
  17.         int countArr1=0;
  18.         int countArr2=0;
  19.         int[] merged= new int[arr1.length+arr2.length];
  20.        
  21.         while (counter<(arr1.length+arr2.length)){
  22.            
  23.             if (arr1[countArr1]<arr2[countArr2]){
  24.                 merged[counter]= arr1[countArr1];
  25.                     counter++;
  26.                     countArr1++;
  27.                 if (countArr1>=arr1.length){
  28.                     while (countArr2< arr2.length)  {
  29.                         merged[counter]= arr2[countArr2];
  30.                         counter++;
  31.                         countArr2++;
  32.                     }
  33.                 }
  34.                
  35.             }
  36.                     else {
  37.                 merged[counter]= arr2[countArr2];
  38.                     counter++;
  39.                     countArr2++;
  40.                        
  41.                         if (countArr2>=arr2.length){
  42.                     while (countArr1<arr1.length) {
  43.                         merged[counter]= arr1[countArr1];
  44.                         counter++;
  45.                         countArr1++;
  46.                     }
  47.                 }
  48.                        
  49.                     }
  50.            
  51.         }
  52.                 return merged;
  53.     }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment