Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. /*
  2. Created by Aditya Ray, 2019-07-23 13:34:28.338424
  3. */
  4.  
  5. // import statements, if any, here
  6. import java.util.Scanner;
  7. public class Practice3
  8. {
  9. public static void main (String[] args)
  10. {
  11. //Scanner input = new Scanner(System.in);
  12. //System.out.println("Enter Array 1: ");
  13. int[] arr1 = { 1, 5, 16, 61,111};
  14. int[] arr2 = { 2, 4, 5, 6 };
  15.  
  16.  
  17. System.out.print("Array 1: ");
  18. display(arr1);
  19. System.out.print("\nArray 2: ");
  20. display(arr2);
  21.  
  22. System.out.print("\nArray after merging: ");
  23. display(merge(arr1,arr2));
  24.  
  25. }
  26. public static int[] merge(int[] arr1, int[] arr2)
  27. {
  28. int i = 0; //index of arr1
  29. int j = 0; //index of arr2
  30. int k = 0; //index of merge
  31. int n1 = arr1.length;
  32. int n2 = arr2.length;
  33. int[] merge = new int[n1 + n2];
  34.  
  35. while(i < n1 && j < n2)
  36. {
  37. if (arr1[i] < arr2[j])
  38. {
  39. merge[k++] = arr1[i++];
  40. }
  41. else
  42. {
  43. merge[k++] = arr2[j++];
  44. }
  45. }
  46. while(i < n1)
  47. {
  48. merge[k++] = arr1[i++];
  49. }
  50. while(j < n2)
  51. {
  52. merge[k++] = arr2[j++];
  53. }
  54. return merge;
  55. }
  56. public static void display(int[] array)
  57. {
  58. for(int x = 0; x < array.length; x++)
  59. {
  60. System.out.print(array[x] + " ");
  61. }
  62.  
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement