Skip to content

Instantly share code, notes, and snippets.

@pavelnganpi
Created August 5, 2014 13:57
Show Gist options
  • Save pavelnganpi/298a73100088becce2a6 to your computer and use it in GitHub Desktop.
Save pavelnganpi/298a73100088becce2a6 to your computer and use it in GitHub Desktop.
Median of two sorted arrays Question: There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n))
public class getMedianOfTwoSortedArrays {
public static int getMedian(int ar1[], int ar2[], int n)
{
int i = 0; /* Current index of i/p array ar1[] */
int j = 0; /* Current index of i/p array ar2[] */
int count;
int m1 = -1, m2 = -1;
/* Since there are 2n elements, median will be average
of elements at index n-1 and n in the array obtained after
merging ar1 and ar2 */
for (count = 0; count <= n; count++)
{
/*Below is to handle case where all elements of ar1[] are
smaller than smallest(or first) element of ar2[]*/
if (i == n)
{
m1 = m2;
m2 = ar2[0];
System.out.println(m2);
break;
}
/*Below is to handle case where all elements of ar2[] are
smaller than smallest(or first) element of ar1[]*/
else if (j == n)
{
System.out.println("2");
m1 = m2;
m2 = ar1[0];
break;
}
if (ar1[i] < ar2[j])
{
m1 = m2; /* Store the prev median */
m2 = ar1[i];
i++;
}
else
{
m1 = m2; /* Store the prev median */
m2 = ar2[j];
j++;
}
}
System.out.println("m1 m2 " +m1+ " " + m2);
return (m1 + m2)/2;
}
public static void main(String[]args){
int ar1[] = {1, 12, 15, 26, 38};
int ar2[] = {2, 13, 17, 30, 45};
int[] ar3 = {0,1,2,3,4};
int[] ar4 = {5,6,7,8,9};
int[] ar5 = {1,2,3,9,10};
int[] ar6 = {4,5,6,7,8};
int[] ar7 = {0,2,4,6,8};
int[] ar8 = {1,3,5,7,9};
int n1 = ar1.length;
int n2 =ar2.length;
if (n1 == n2)
System.out.println("Median is " + getMedian(ar5, ar6, n1));
else
System.out.println("Doesn't work for arrays of unequal size");
}
}
@ShawnReddy
Copy link

Could you please give me the pseudocode?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment