Merging two arrays as alternative elements of third array in java



MergeAlernateElementOfTwoSplittedArrayIntoThirdArray 

  The goal of the program is to merge two arrays into a third array by alternating their elements.
1. Program Overview
The program first splits an input array (arr) into two separate arrays (first and second). It then merges these two arrays into a third array (third), alternating elements from each array. Initialization:
The main method begins by initializing an integer array arr with 8 elements. It calculates the length len of this array. Two new arrays, first and second, are created to hold the split halves of arr. The first array is of size (len + 1) / 2 to handle both even and odd lengths, ensuring the first half gets the extra element if the length is odd. The second array is the remainder (len - first.length). Splitting the Array:
The splitGivenArrayInTwo method is called to divide arr into first and second arrays. Printing the Arrays:
The print method is called to display the contents of first and second arrays. Merging the Arrays:
The mergeAndReturnThirdArrayWithAlernateElements method is called to merge first and second arrays into third by alternating elements. Final Print:
The print method is called again to display the contents of the merged third array.

import java.util.Arrays;
public class MergeTwoArraysWithAlternateElements {
    public static void main(String[] args) {

        int[] arr = {10, 20, 30, 50, 60, 70, 80, 10};
        int len = arr.length;

        int first[] = new int[(len + 1) / 2];
        int second[] = new int[len - first.length];

        splitGivenArrayInTwo(arr, len, first, second);

        print(first);

        print(second);

        int[] third = mergeAndReturnThirdArrayWithAlernateElements(first, second);

        print(third);


    }

    private static int[] mergeAndReturnThirdArrayWithAlernateElements(int[] temp, int[] temp1) {
        int result[] = new int[temp.length + temp1.length];

        int j = 0, k = 0;
        for (int i = 0; i < result.length; i++) {

            if (i % 2 == 0) {

                result[i] = temp[j++];

            } else {

                result[i] = temp1[k++];

            }

        }
        return result;
    }

    private static void splitGivenArrayInTwo(int[] arr, int len, int[] temp, int[] temp1) {
        for (int i = 0; i < len; i++) {
            if (i < temp.length) {
                temp[i] = arr[i];
            } else {
                temp1[i - temp.length] = arr[i];

            }

        }
    }


    static void print(int[] t) {

        System.out.println(Arrays.toString(t));


    }
}

OutPut:

[10, 20, 30, 50]
[60, 70, 80, 10]
[10, 60, 20, 70, 30, 80, 50, 10]

Comments

Popular posts from this blog

First Repeating character in a string

Index of first repeated character in a string.

Usage of map,max,sorted,comparing java 8 methods