double findMedianSortedArrays(int A[], int m, int B[], int n)
 {
     if((m+n)%2==1)
     {
         return (double)findMedianIndex(A,m,B,n,(m+n+1)/2);
     }
     return ((double)findMedianIndex(A,m,B,n,(m+n)/2)+(double)findMedianIndex(A,m,B,n,(m+n)/2+1))/2;
 }
/*Computes the median of each group of 5 elements and stores
  it as the first element of the group (left). Recursively does this
  till there is only one group and hence only one Median */
mwSize findMedianOfMedians(mwSize left, mwSize right)
{
    mwSize i, shift, step, tmp;
    mwSize endIndex, medianIndex;
           
    if (left==right) return left;
   
    shift = 1;
    while (shift <= (right-left))
    {
        step=shift*5;
        for (i=left; i<=right; i+=step)
        {
            if ((endIndex=i+step-1)>=right)
                endIndex=right;
            medianIndex = findMedianIndex(i, endIndex, shift);
            /* Swap pos[i] with pos[medianIndex] */
            tmp = pos[i];
            pos[i] = pos[medianIndex];
            pos[medianIndex] = tmp;
        }
        shift = step;
    }
    return left;
} /* findMedianOfMedians */
 int findMedianIndex(int A[], int m, int B[], int n, int k)
 {
     if(0==m)
     {
         return B[k-1];
     }
     if(0==n)
     {
         return A[k-1];
     }
     if(1==k)
     {
         return min(A[0], B[0]);
     }
     
     int i=min(m,k/2);
     int j=min(n,k/2);
     
     if(A[i-1]<B[j-1])
     {
         return findMedianIndex(A+i,m-i,B,n,k-i);
     }
     return findMedianIndex(A,m,B+j,n-j,k-j);
 }
Exemple #4
0
//Computes the median of each group of 5 elements and stores
//it as the first element of the group. Recursively does this
//till there is only one group and hence only one Median
double findMedianOfMedians(int rows, int cols, int colToSortOn, double * array, 
	int left, int right)
{
	double * colToSort = array+colToSortOn*rows;
	if(left == right)
		return colToSort[left];
 
	int i, shift = 1;
	while(shift <= (right - left)) {
		for(i = left; i <= right; i+=shift*5) {
			int endIndex = (i + shift*5 - 1 < right) ? i + shift*5 - 1 : right;

			int medianIndex = findMedianIndex(rows, cols, colToSortOn, array, 
				i, endIndex, shift);

			swapRows(rows, cols, array, i, medianIndex);
		}
		shift *= 5;
	}
	return colToSort[left];
}