Advertisement
rishu110067

Merge One Sorted Array Into Another Solution 2

Jan 28th, 2022 (edited)
727
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     static ArrayList<Integer> merge_one_into_another(ArrayList<Integer> arr1, ArrayList<Integer> arr2) {
  2.         int i = arr1.size()-1;
  3.         int j = arr1.size()-1;
  4.         int idx = arr2.size()-1;
  5.        
  6.         // sorting from right side
  7.         while(i >= 0 && j >= 0)  {
  8.             if(arr1.get(i) >= arr2.get(j)) {
  9.                 arr2.set(idx, arr1.get(i));
  10.                 arr1.set(i, 0);
  11.                 i--;
  12.                 idx--;
  13.             } else {
  14.                 arr2.set(idx, arr2.get(j));
  15.                 arr2.set(j, 0);
  16.                  j--;
  17.                  idx--;
  18.             }    
  19.         }
  20.         // put remaining elements in arr1 to arr2
  21.         while(i >= 0)
  22.         {
  23.             arr2.set(idx, arr1.get(i));
  24.             arr1.set(i, 0);
  25.             i--;
  26.             idx--;
  27.         }
  28.    
  29.         return arr2;
  30.     }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement