Suppose we have 2 sorted arrays a1={1,3,5,7} and a2={2,4,6}.We have to merge this 2 arrays to generate below result
a3={1,2,3,4,5,6,7}
Sample Program:-
public class MergeSortedArray {
public static void main(String[] args) {
int[] ar1 = { 1, 3, 5, 7 };
int[] ar2 = { 2, 4, 6, 8 };
int mergedArray[] = merge(ar1, ar2);
System.out.print("\nMerged array: ");
for (int i = 0; i < mergedArray.length; i++)
System.out.print(mergedArray[i] + " ");
}
private static int[] merge(int[] ar1, int[] ar2) {
int mergedArray[] = new int[ar1.length + ar2.length];
int ar1Index = 0, ar2Index = 0, mergedArrayIndex = 0;
while (ar1Index < ar1.length && ar2Index < ar2.length)
if (ar1[ar1Index] < ar2[ar2Index])
mergedArray[mergedArrayIndex++] = ar1[ar1Index++];
else
mergedArray[mergedArrayIndex++] = ar2[ar2Index++];
while (ar1Index < ar1.length)
mergedArray[mergedArrayIndex++] = ar1[ar1Index++];
while (ar2Index < ar2.length)
mergedArray[mergedArrayIndex++] = ar2[ar2Index++];
return mergedArray;
}
}
Output:-
Merged array: 1 2 3 4 5 6 7 8
Enjoy Coding.
No comments:
Post a Comment