USING JAVA ONLY
Merge two 1D arrays into a single array. take one value from each array at a time.
Sample:
array 1: 1,2,3,4,5
array 2: 2,4
new array: 1,2,2,4,3,4,5
import java.util.Scanner; public class MergeArrays { public static int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length]; int maxLength = a.length, index = 0; if (b.length > maxLength) maxLength = b.length; for (int i = 0; i < maxLength; i++) { if (i < a.length) { result[index++] = a[i]; } if (i < b.length) { result[index++] = b[i]; } } return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter size of first array: "); int n1 = in.nextInt(); int[] arr1 = new int[n1]; System.out.print("Enter " + n1 + " numbers: "); for (int i = 0; i < n1; ++i) { arr1[i] = in.nextInt(); } System.out.print("Enter size of second array: "); int n2 = in.nextInt(); int[] arr2 = new int[n2]; System.out.print("Enter " + n2 + " numbers: "); for (int i = 0; i < n2; ++i) { arr2[i] = in.nextInt(); } int[] arr = merge(arr1, arr2); System.out.print("new array: "); for (int i = 0; i < arr.length; ++i) { System.out.print(arr[i] + " "); } System.out.println(); } }
Get Answers For Free
Most questions answered within 1 hours.