Merge two sorted arrays in a such a way that a newly generated array will be sorted.
Merge two sorted arrays in a such a way that a newly generated array will be sorted.
Here we are going to take two pointers one for each.
Algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.omt.learn; public class SortedTwoArrayMerge { public static void main(String[] args) { int a[] = { 3, 5, 7, 8, 8, 9, 10 }; int b[] = { 3, 4, 6, 7, 11 }; int result[] = mergeTwoSortedArrays(a, b); for (int i : result) { System.out.print(i + " "); } } public static int[] mergeTwoSortedArrays(int a[], int b[]) { int[] r = new int[a.length + b.length]; int p1 = 0; int p2 = 0; int index = 0; while (p1 < a.length && p2 < b.length) { if (a[p1] < b[p2]) { r[index] = a[p1]; p1++; } else { r[index] = b[p2]; p2++; } index++; } while (p1 < a.length) { r[index++] = a[p1++]; } while (p2 < b.length) { r[index++] = b[p2++]; } return r; } } |