USING JAVA ONLY - THE NEW ARRAY IS NOT JUST THE VALUES IN INCREASING ORDER
Merge two 1D arrays into a single array. take one value from each array at a time. The new array takes a value from array 1, than one from array two, and keeps repeating until all values are in the new array.
Sample:
array 1: 1,2,3,4,5
array 2: 2,4
new array: 1,2,2,4,3,4,5
Sample 2:
array 1: is 8,2,4,7,2,6,2
array 2: 4,7,3
new array: 8,4,2,7,4,3,7,2,6,2
import java.util.Scanner; public class MergeIntArrays { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("array 1: "); String[] s1 = scanner.nextLine().split(","); int arr1[] = new int[s1.length]; for(int i = 0;i<arr1.length;i++){ arr1[i] = Integer.parseInt(s1[i]); } System.out.print("array 2: "); String[] s2 = scanner.nextLine().split(","); int arr2[] = new int[s2.length]; for(int i = 0;i<arr2.length;i++){ arr2[i] = Integer.parseInt(s2[i]); } int arr[] = new int[arr1.length+arr2.length]; int i = 0, k =0; while(i<arr1.length && i<arr2.length){ arr[k++] = arr1[i]; arr[k++] = arr2[i]; i++; } while(i<arr1.length){ arr[k++] = arr1[i++]; } while(i<arr2.length){ arr[k++] = arr2[i++]; } System.out.print("new array: "); for(int j = 0;j<arr.length;j++){ if(j == 0){ System.out.print(arr[j]); } else{ System.out.print(","+arr[j]); } } System.out.println(); } }
Get Answers For Free
Most questions answered within 1 hours.