Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Created by Aditya Ray, 2019-07-23 13:34:28.338424
- */
- // import statements, if any, here
- import java.util.Scanner;
- public class Practice3
- {
- public static void main (String[] args)
- {
- //Scanner input = new Scanner(System.in);
- //System.out.println("Enter Array 1: ");
- int[] arr1 = { 1, 5, 16, 61,111};
- int[] arr2 = { 2, 4, 5, 6 };
- System.out.print("Array 1: ");
- display(arr1);
- System.out.print("\nArray 2: ");
- display(arr2);
- System.out.print("\nArray after merging: ");
- display(merge(arr1,arr2));
- }
- public static int[] merge(int[] arr1, int[] arr2)
- {
- int i = 0; //index of arr1
- int j = 0; //index of arr2
- int k = 0; //index of merge
- int n1 = arr1.length;
- int n2 = arr2.length;
- int[] merge = new int[n1 + n2];
- while(i < n1 && j < n2)
- {
- if (arr1[i] < arr2[j])
- {
- merge[k++] = arr1[i++];
- }
- else
- {
- merge[k++] = arr2[j++];
- }
- }
- while(i < n1)
- {
- merge[k++] = arr1[i++];
- }
- while(j < n2)
- {
- merge[k++] = arr2[j++];
- }
- return merge;
- }
- public static void display(int[] array)
- {
- for(int x = 0; x < array.length; x++)
- {
- System.out.print(array[x] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement