Solution:
Merge two sorted array into new sorrted array
input A 1,2,3,4,5(asc)
input B 10,9,8,7,6(dec)
output 1,2,3,4,5,6,7,8,9,10(asc)
package array;
/* merge two sorted array into new sorrted array*/
public class Merge2array {
public int arr1[];
public int arr2[];
public int newarr[];
public Merge2array(int arr1[], int arr2[]) {
int i = 0, j = 0;
this.arr1 = new int[arr1.length];
this.arr2 = new int[arr2.length];
for (int a : arr1) {
// System.out.print(a + " ");
this.arr1[i++] = a;
}
for (int b : arr2) {
// System.out.print(b + " ");
this.arr2[j++] = b;
}
this.newarr = new int[arr1.length + arr2.length];
merge();
}
public void merge() {
int i = 0, k = 0;
int j = arr2.length - 1;
while (arr1.length + arr2.length - 1 > k) {
if (arr1[i] < arr2[j])
newarr[k++] = arr1[i++];
else
newarr[k++] = arr2[j--];
if (i == arr1.length)
for (; j >= 0;)
newarr[k++] = arr2[j--];
else if (j < 0)
for (; i < arr1.length;)
newarr[k++] = arr1[i++];
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
// System.out.println();
for (int a : newarr)
s.append(a + ",");
return s.toString();
}
public static void main(String[] args) {
int a[] = { 1, 8, 18, 28, 50 };
int b[] = { 51, 27, 2, 1 };
System.out.println(new Merge2array(a, b));
}
}
OUTPUT:
1,1,2,8,18,27,28,50,51,