merge arrays java code example
Example 1: concatenate two arrays in java
import java.util.Arrays;
public class Concat {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int aLen = array1.length;
int bLen = array2.length;
int[] result = new int[aLen + bLen];
System.arraycopy(array1, 0, result, 0, aLen);
System.arraycopy(array2, 0, result, aLen, bLen);
System.out.println(Arrays.toString(result));
}
}
Example 2: Merge sort java
public class JavaMergeSort
{
void sorting(int[] num, int left, int main, int right)
{
int list1 = main - left + 1;
int list2 = right - main;
int[] L = new int[list1];
int[] R = new int[list2];
for(int a = 0; a < list1; ++a)
L[a] = num[left + a];
for(int b = 0; b < list2; ++b)
R[b] = num[main + 1+ b];
int p = 0, q = 0;
int r = left;
while(p < list1 && q < list2)
{
if(L[p] <= R[q])
{
num[r] = L[p];
p++;
}
else
{
num[r] = R[q];
q++;
}
r++;
}
while(p < list1)
{
num[r] = L[p];
p++;
r++;
}
while(q < list2)
{
num[r] = R[q];
q++;
r++;
}
}
void sort(int[] arrNum, int l, int r)
{
if(l < r)
{
int m = (l + r) / 2;
sort(arrNum, l, m);
sort(arrNum , m+1, r);
sorting(arrNum, l, m, r);
}
}
static void displayArray(int[] arr)
{
int number = arr.length;
for(int a = 0; a < number; ++a)
System.out.print(arr[a] + " ");
System.out.println();
}
public static void main(String[] args)
{
int[] arrNumbers = {33, 00, 55, 11, 22, 44};
System.out.println("Before sorting - ");
displayArray(arrNumbers);
JavaMergeSort obj = new JavaMergeSort();
obj.sort(arrNumbers, 0, arrNumbers.length - 1);
System.out.println("\nAfter sorting - ");
displayArray(arrNumbers);
}
}