Example #1
0
/* A recursive function to get the median of ar1[] and ar2[]
   using binary search */
int getMedianRec(int ar1[], int ar2[], int left, int right, int n)
{
    int i, j;
 
    /* We have reached at the end (left or right) of ar1[] */
    if (left > right)
        return getMedianRec(ar2, ar1, 0, n-1, n);
 
    i = (left + right)/2;
    j = n - i - 1;  /* Index of ar2[] */
 
    /* Recursion terminates here.*/
    if (ar1[i] > ar2[j] && (j == n-1 || ar1[i] <= ar2[j+1]))
    {
        /* ar1[i] is decided as median 2, now select the median 1
           (element just before ar1[i] in merged array) to get the
           average of both*/
        if (i == 0 || ar2[j] > ar1[i-1])
            return (ar1[i] + ar2[j])/2;
        else
            return (ar1[i] + ar1[i-1])/2;
    }
 
    /*Search in left half of ar1[]*/
    else if (ar1[i] > ar2[j] && j != n-1 && ar1[i] > ar2[j+1])
        return getMedianRec(ar1, ar2, left, i-1, n);
 
    /*Search in right half of ar1[]*/
    else /* ar1[i] is smaller than both ar2[j] and ar2[j+1]*/
        return getMedianRec(ar1, ar2, i+1, right, n);
}
Example #2
0
int getMedianRec(int a[], int b[], int left, int right, int n){
    int i, j;
    if(left > right)
        return getMedianRec(b, a, 0, n-1, n);
    i = (left + right)/2;
    j = n - i - 1;
    if(b[j] < a[i] && (j == n-1 || a[i] <= b[j+1])){
        if(i == 0 || b[j] > a[i-1]) 
            return (a[i] + b[j])/2;
        else return (a[i] + a[i-1])/2;
    }
    else if(a[i] > b[j] &&  j != n-1 && a[i] > b[j+1]){
        return getMedianRec(a, b, left, i-1, n);
    }
    else return getMedianRec(a, b, i+1, right, n);
}
Example #3
0
/* This function returns median of ar1[] and ar2[].
   Assumptions in this function:
   Both ar1[] and ar2[] are sorted arrays
   Both have n elements */
int getMedian(int ar1[], int ar2[], int n)
{
   // If all elements of array 1 are smaller then
   // median is average of last element of ar1 and
   // first element of ar2
   if (ar1[n-1] < ar2[0])
     return (ar1[n-1]+ar2[0])/2;
 
   // If all elements of array 1 are smaller then
   // median is average of first element of ar1 and
   // last element of ar2
   if (ar2[n-1] < ar1[0])
     return (ar2[n-1]+ar1[0])/2;
 
   return getMedianRec(ar1, ar2, 0, n-1, n);
}
Example #4
0
int getMedian(int a[], int b[], int n){
    return getMedianRec(a, b, 0, n-1, n);
}
Example #5
0
/* This function returns median of ar1[] and ar2[].
   Assumptions in this function:
   Both ar1[] and ar2[] are sorted arrays
   Both have n elements */
int getMedian(int ar1[], int ar2[], int n)
{
    return getMedianRec(ar1, ar2, 0, n-1, n);
}