Created
August 4, 2014 15:18
-
-
Save pavelnganpi/ad1b23e044a2d9b3e89f to your computer and use it in GitHub Desktop.
There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MergeAnArrayOfSizeNIntoAnotherArrayOfSizeMPlusN { | |
static int NA=-1; | |
//move m elements to end of array | |
public static int[] moveToEnd(int[] mPlusN){ | |
int size = mPlusN.length; | |
int i = size-1; | |
int j = size-1; | |
for(i = size-1; i>=0;i--){ | |
if(mPlusN[i] !=NA){ | |
mPlusN[j]=mPlusN[i]; | |
j--; | |
} | |
} | |
return mPlusN; | |
} | |
//merge arrays from n element from mplusN to its end and from | |
//0 index of n[] to its end | |
public static void merge(int[] mPlusN, int[] N, int mPlusNcount, int nCount){ | |
int k=0; | |
int i=nCount; | |
int j=0; | |
while(k<mPlusNcount){ | |
if(i<mPlusNcount && (mPlusN[i] <= N[j]) || (j==nCount)){ | |
mPlusN[k]=mPlusN[i]; | |
k++; | |
i++; | |
} | |
else{ | |
mPlusN[k]=N[j]; | |
j++; | |
k++; | |
} | |
} | |
} | |
public static void printArray(int arr[], int size) | |
{ | |
int i; | |
for (i=0; i < size; i++) | |
System.out.print(arr[i] + " "); | |
System.out.print("\n"); | |
} | |
public static void main(String[]args){ | |
int mPlusN[] = {2, 8, NA, NA, NA, 13, NA, 15, 20}; | |
int N[] = {5, 7, 9, 25}; | |
int n = N.length; | |
int m =mPlusN.length; | |
/*Move the m elements at the end of mPlusN*/ | |
moveToEnd(mPlusN); | |
/*Merge N[] into mPlusN[] */ | |
merge(mPlusN, N, m, n); | |
/* Print the resultant mPlusN */ | |
printArray(mPlusN, m); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment