std::vector<double> getModifiedZscore(const vector<TYPE> &data, const bool sorted) { if (data.size() < 3) { std::vector<double> Zscore(data.size(), 0.); return Zscore; } std::vector<double> MADvec; double tmp; size_t num_data = data.size(); // cache since it is frequently used double median = getMedian(data, num_data, sorted); typename vector<TYPE>::const_iterator it = data.begin(); for (; it != data.end(); ++it) { tmp = static_cast<double>(*it); MADvec.push_back(fabs(tmp - median)); } double MAD = getMedian(MADvec, num_data, sorted); if (MAD == 0.) { std::vector<double> Zscore(data.size(), 0.); return Zscore; } MADvec.clear(); std::vector<double> Zscore; it = data.begin(); for (; it != data.end(); ++it) { tmp = static_cast<double>(*it); Zscore.push_back(0.6745 * fabs((tmp - median) / MAD)); } return Zscore; }
//************************************************************* std::pair<Double_t,Double_t> getMAD(TH1F *histo) //************************************************************* { int nbins = histo->GetNbinsX(); Double_t median = getMedian(histo).first; Double_t x_lastBin = histo->GetBinLowEdge(nbins+1); const char *HistoName =histo->GetName(); TString Finalname = Form("resMed%s",HistoName); TH1F *newHisto = new TH1F(Finalname,Finalname,nbins,0.,x_lastBin); Double_t *residuals = new Double_t[nbins]; Double_t *weights = new Double_t[nbins]; for (int j = 0; j < nbins; j++) { residuals[j] = TMath::Abs(median - histo->GetBinCenter(j+1)); weights[j]=histo->GetBinContent(j+1); newHisto->Fill(residuals[j],weights[j]); } Double_t theMAD = (getMedian(newHisto).first)*1.4826; newHisto->Delete(""); std::pair<Double_t,Double_t> result; result = std::make_pair(theMAD,theMAD/histo->GetEntries()); return result; }
double findMedianSortedArrays(int A[], int m, int B[], int n) { if( (m+n)%2 == 0 ) return (getMedian(A,m,B,n, (m+n)/2) + getMedian(A,m,B,n, (m+n)/2+1)) /2.0 ; else return getMedian(A,m,B,n, (m+n)/2+1); }
Rect2d TrackerMedianFlowImpl::vote(const std::vector<Point2f>& oldPoints,const std::vector<Point2f>& newPoints,const Rect2d& oldRect,Point2f& mD){ static int iteration=0;//FIXME -- we don't want this static var in final release Rect2d newRect; Point2d newCenter(oldRect.x+oldRect.width/2.0,oldRect.y+oldRect.height/2.0); int n=(int)oldPoints.size(); std::vector<double> buf(std::max(n*(n-1)/2,3),0.0); if(oldPoints.size()==1){ newRect.x=oldRect.x+newPoints[0].x-oldPoints[0].x; newRect.y=oldRect.y+newPoints[0].y-oldPoints[0].y; newRect.width=oldRect.width; newRect.height=oldRect.height; return newRect; } double xshift=0,yshift=0; for(int i=0;i<n;i++){ buf[i]=newPoints[i].x-oldPoints[i].x; } xshift=getMedian(buf,n); newCenter.x+=xshift; for(int i=0;i<n;i++){ buf[i]=newPoints[i].y-oldPoints[i].y; } yshift=getMedian(buf,n); newCenter.y+=yshift; mD=Point2f((float)xshift,(float)yshift); if(oldPoints.size()==1){ newRect.x=newCenter.x-oldRect.width/2.0; newRect.y=newCenter.y-oldRect.height/2.0; newRect.width=oldRect.width; newRect.height=oldRect.height; return newRect; } double nd,od; for(int i=0,ctr=0;i<n;i++){ for(int j=0;j<i;j++){ nd=l2distance(newPoints[i],newPoints[j]); od=l2distance(oldPoints[i],oldPoints[j]); buf[ctr]=(od==0.0)?0.0:(nd/od); ctr++; } } double scale=getMedian(buf,n*(n-1)/2); dprintf(("iter %d %f %f %f\n",iteration,xshift,yshift,scale)); newRect.x=newCenter.x-scale*oldRect.width/2.0; newRect.y=newCenter.y-scale*oldRect.height/2.0; newRect.width=scale*oldRect.width; newRect.height=scale*oldRect.height; /*if(newRect.x<=0){ exit(0); }*/ dprintf(("rect old [%f %f %f %f]\n",oldRect.x,oldRect.y,oldRect.width,oldRect.height)); dprintf(("rect [%f %f %f %f]\n",newRect.x,newRect.y,newRect.width,newRect.height)); iteration++; return newRect; }
// A wrapper function around findMedianUtil(). This function makes // sure that smaller array is passed as first argument to findMedianUtil float findMedian( int A[], int N, int B[], int M )//leetcode acepted ! { if (N == 0) return getMedian(B,M); if(M == 0) return getMedian(A,N); if ( N > M ) return findMedianUtil( B, M, A, N ); return findMedianUtil( A, N, B, M ); }
int getMedian(int a[], int b[], int n){ if(n <= 0) return -1; if(n == 1) return (a[0] + b[0])/2; if(n == 2) return (max(a[0], b[0]) + min(a[1], b[1]))/2; int m1 = median(a, n); int m2 = median(b, n); if(m1 == m2) return m1; if(m1 < m2) { if(n%2 == 0) return getMedian(a+n/2-1, b, n-n/2+1); else return getMedian(a+n/2, b, n-n/2); }else { if(n%2 == 0) return getMedian(b+n/2-1, a, n-n/2+1); else return getMedian(b+n/2, a, n-n/2); } }
List* List::split(bool first){ List* newList; int len; Entry_Sonodabe* newEntries; if(first){ len = length/2; newEntries = new Entry_Sonodabe[len]; int i = 0; Node* cur = sentinel->next; while(cur!= getMedian()){ newEntries[i].identifier = cur->data->identifier; newEntries[i].x = cur->data->x; newEntries[i].y = cur->data->y; newEntries[i].census1 = cur->data->census1; newEntries[i].census2 = cur->data->census2; newEntries[i].r = cur->data->r; newEntries[i].g = cur->data->g; cur = cur->next; i++; } }else{ if(len%2 == 0) len = length-length/2-1; else len = length-length/2; newEntries = new Entry_Sonodabe[len]; Node* cur = getMedian()->next; int i = 0; while(cur!= sentinel){ newEntries[i].identifier = cur->data->identifier; newEntries[i].x = cur->data->x; newEntries[i].y = cur->data->y; newEntries[i].census1 = cur->data->census1; newEntries[i].census2 = cur->data->census2; newEntries[i].r = cur->data->r; newEntries[i].g = cur->data->g; cur = cur->next; i++; } } newList = new List(newEntries, len, !isX); return newList; }
int main(){ int a[] = {1,3,5,7,9}; int b[] = {2,4,6,8,10}; int size = sizeof(a)/sizeof(a[0]); printf("%d\n", getMedian(a, b, size)); return 0; }
void median_filter( int* in, int* out, int* window, int gridLen, int filtLen) { int filtRad = filtLen / 2; #pragma omp parallel for for (int y = 0; y < gridLen; y++) { for (int x = 0; x < gridLen; x++) { int w_idx = 0; for (int dy = -filtRad; dy <= filtRad; dy++) { for (int dx = -filtRad; dx <= filtRad; dx++) { // gather the values in the window int gy, gx; if (y + dy < 0) {gy = 0;} else if (y + dy >= gridLen) {gy = gridLen - 1;} else {gy = y + dy;} if (x + dx < 0) {gx = 0;} else if (x + dx >= gridLen) {gx = gridLen - 1;} else {gx = x + dx;} window[w_idx] = in[gy * gridLen + gx]; w_idx++; } } int median = getMedian(window, filtLen * filtLen); out[y * gridLen + x] = median; } } }
int main ( int argc, char *argv[] ) { int n, i, x; medHeap H; srand((unsigned int)time(NULL)); if (argc > 1) n = atoi(argv[1]); else scanf("%d", &n); H = initMedHeap(n); printf("\n+++ MedHeap initialized\n"); printf("\n+++ Going to insert elements one by one in MedHeap\n"); for (i=0; i<n; ++i) { x = 1 + rand() % 9999; H = insMedHeap(H,x); printf(" Insert(%4d) done. Current median = %4d.\n", x, getMedian(H)); } H = medHeapSort(H); printf("\n+++ Median Heap Sort done\n"); printArray(H); free(H.val); exit(0); }
int main(){ //int a[] = {1, 3, 5, 7, 9}; int a[] = {1, 3, 7, 15, 22}; int b[] = {2, 14, 16, 18, 100}; printf("%d\n", getMedian(a, b, 5)); }
int alignmentsSelect(std::vector<Chain*>& alignment_strings, Chain* query, float threshold) { int amino_acid_num = 26; float median = kLog_2_20; int* amino_acid_nums = new int[amino_acid_num]; for (int i = 0; i < amino_acid_num; ++i) { amino_acid_nums[i] = 0; } int query_len = chainGetLength(query); float* pos_freq = new float[query_len]; for (int i = 0; i < query_len; ++i) { pos_freq[i] = 0.0; } char c; int i, valid; for (i = 1; median > threshold && i <= (int) alignment_strings.size(); ++i) { for (int j = 0; j < query_len; ++j) { valid = 0; for (int k = 0; k < i; ++k) { c = chainGetChar(alignment_strings[k], j); if (c != 'X') { valid++; amino_acid_nums[(int) c - 'A']++; } } for (int k = 0; k < amino_acid_num; ++k) { if (amino_acid_nums[k] != 0) { pos_freq[j] += amino_acid_nums[k] / (float) valid * log2f(amino_acid_nums[k] / (float) valid); } } pos_freq[j] += kLog_2_20; for (int k = 0; k < amino_acid_num; ++k) { if (amino_acid_nums[k] != 0) { amino_acid_nums[k] = 0; } } } median = getMedian(pos_freq, query_len); for (int j = 0; j < query_len; ++j) { pos_freq[j] = 0.0; } } delete[] pos_freq; delete[] amino_acid_nums; return i - 1; }
void TrackerMedianFlowImpl::check_NCC(const Mat& oldImage,const Mat& newImage, const std::vector<Point2f>& oldPoints,const std::vector<Point2f>& newPoints,std::vector<bool>& status){ std::vector<float> NCC(oldPoints.size(),0.0); Size patch(30,30); Mat p1,p2; for (int i = 0; i < (int)oldPoints.size(); i++) { getRectSubPix( oldImage, patch, oldPoints[i],p1); getRectSubPix( newImage, patch, newPoints[i],p2); const int N=900; double s1=sum(p1)(0),s2=sum(p2)(0); double n1=norm(p1),n2=norm(p2); double prod=p1.dot(p2); double sq1=sqrt(n1*n1-s1*s1/N),sq2=sqrt(n2*n2-s2*s2/N); double ares=(sq2==0)?sq1/abs(sq1):(prod-s1*s2/N)/sq1/sq2; NCC[i] = (float)ares; } float median = getMedian(NCC); for(int i = 0; i < (int)oldPoints.size(); i++) { status[i] = status[i] && (NCC[i]>median); } }
bool TrackerMedianFlowImpl::medianFlowImpl(Mat oldImage,Mat newImage,Rect2d& oldBox){ std::vector<Point2f> pointsToTrackOld,pointsToTrackNew; Mat oldImage_gray,newImage_gray; cvtColor( oldImage, oldImage_gray, COLOR_BGR2GRAY ); cvtColor( newImage, newImage_gray, COLOR_BGR2GRAY ); //"open ended" grid for(int i=0;i<params.pointsInGrid;i++){ for(int j=0;j<params.pointsInGrid;j++){ pointsToTrackOld.push_back( Point2f((float)(oldBox.x+((1.0*oldBox.width)/params.pointsInGrid)*j+.5*oldBox.width/params.pointsInGrid), (float)(oldBox.y+((1.0*oldBox.height)/params.pointsInGrid)*i+.5*oldBox.height/params.pointsInGrid))); } } std::vector<uchar> status(pointsToTrackOld.size()); std::vector<float> errors(pointsToTrackOld.size()); calcOpticalFlowPyrLK(oldImage_gray, newImage_gray,pointsToTrackOld,pointsToTrackNew,status,errors,Size(3,3),5,termcrit,0); dprintf(("\t%d after LK forward\n",(int)pointsToTrackOld.size())); std::vector<Point2f> di; for(int i=0;i<(int)pointsToTrackOld.size();i++){ if(status[i]==1){ di.push_back(pointsToTrackNew[i]-pointsToTrackOld[i]); } } std::vector<bool> filter_status; check_FB(oldImage_gray,newImage_gray,pointsToTrackOld,pointsToTrackNew,filter_status); check_NCC(oldImage_gray,newImage_gray,pointsToTrackOld,pointsToTrackNew,filter_status); // filter for(int i=0;i<(int)pointsToTrackOld.size();i++){ if(!filter_status[i]){ pointsToTrackOld.erase(pointsToTrackOld.begin()+i); pointsToTrackNew.erase(pointsToTrackNew.begin()+i); filter_status.erase(filter_status.begin()+i); i--; } } dprintf(("\t%d after LK backward\n",(int)pointsToTrackOld.size())); if(pointsToTrackOld.size()==0 || di.size()==0){ return false; } Point2f mDisplacement; oldBox=vote(pointsToTrackOld,pointsToTrackNew,oldBox,mDisplacement); std::vector<double> displacements; for(int i=0;i<(int)di.size();i++){ di[i]-=mDisplacement; displacements.push_back(sqrt(di[i].ddot(di[i]))); } if(getMedian(displacements,(int)displacements.size())>10){ return false; } return true; }
inline Timer::~Timer () { switch (option) { case raw_data_cerr: for (auto result : results) { // clang-format off std::cerr << name << "," << result / Timer::usec_factor << "." << std::setw(6) << std::setfill('0') << result % Timer::usec_factor << std::endl; // clang-format on } break; case median_cerr: std::cerr << name << "," << getMedian () << std::endl; break; case quiet: break; } }
//get most(best) available label from histogram int kNearestNeighFilter::getMostLabel(const ivector& histogram, const imatrix& src, const int& row, const int& col) const{ int numOfMax = 0; int maxIndex = -1; // first index, which is max int max = 0; // for(int i=0;i<histoSize;++i) { if(histogram.at(i) < max); // for speed up (probability) else if(histogram.at(i) > max) { max = histogram.at(i); numOfMax = 1; maxIndex = i; } else //if(histogram.at(i) == max) ++numOfMax; } //is there more than one possibility ? if (numOfMax == 1) return maxIndex; // is the kernel center one of the max's? else if(histogram.at(src.at(row,col)) == max) return src.at(row,col); else return getMedian(histogram,max,numOfMax); };
medHeap insMedHeap ( medHeap H, int x ) { int m; if ((H.n1 == 0) && (H.n2 == 0)) { /* Insertion in an empty heap */ H.val[H.capacity-1] = x; H.n2 = 1; } else if (H.n1 + H.n2 == H.capacity) { /* Insertion in a full heap */ fprintf(stderr, "*** Error in insMedHeap: Heap is full\n"); } else { m = getMedian(H); /* Get the current median */ if (x <= m) { /* Insert in maxheap */ if (H.n2 == H.n1) { H = delMaxHeap(H); /* Deletion of m from the smaller half */ H = insMinHeap(H,m); /* Insertion of m in the larger half */ } H = insMaxHeap(H,x); /* Insertion of x in the smaller half */ } else { /* Insert in minheap */ if (H.n2 == H.n1 + 1) { H = delMinHeap(H); /* Deletion of m from the larger half */ H = insMaxHeap(H,m); /* Insertion of m in the smaller half */ } H = insMinHeap(H,x); /* Insertion of x in the larger half */ } } return H; }
Node* BinaryTree::createBTree(int sortedArray[], int start, int end) { Node* currentNode = new Node; currentNode->data = getMedian(sortedArray, end+1); currentNode->left = createBTree(sortedArray, 0,end/2 -1); currentNode->right = createBTree(sortedArray, end/2 + 1 , end); return currentNode; }
double getMedian(int a[], int m, int b[], int n, int median_) { if (m > n) return getMedian(b, n, a, m, median_); if (m == 0) return b[median_ - 1]; if (median_ == 1) return std::min(a[0], b [0]); int pa = std::min(median_/2, m), pb = median_ - pa; if (a[pa - 1] < b[pb - 1]) return getMedian(a + pa, m - pa, b, n, median_ - pa); else if (a[pa - 1] > b[pb - 1]) return getMedian(a, m, b + pb, n - pb, median_ - pb); else return a[pa - 1]; }
void TLDDetector::ocl_batchSrSc(const Mat_<uchar>& patches, double *resultSr, double *resultSc, int numOfPatches) { UMat devPatches = patches.getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY); UMat devPositiveSamples = posExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY); UMat devNegativeSamples = negExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY); UMat devPosNCC(MAX_EXAMPLES_IN_MODEL, numOfPatches, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY); UMat devNegNCC(MAX_EXAMPLES_IN_MODEL, numOfPatches, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY); ocl::Kernel k; ocl::ProgramSource src = ocl::tracking::tldDetector_oclsrc; String error; ocl::Program prog(src, String(), error); k.create("batchNCC", prog); if (k.empty()) printf("Kernel create failed!!!\n"); k.args( ocl::KernelArg::PtrReadOnly(devPatches), ocl::KernelArg::PtrReadOnly(devPositiveSamples), ocl::KernelArg::PtrReadOnly(devNegativeSamples), ocl::KernelArg::PtrWriteOnly(devPosNCC), ocl::KernelArg::PtrWriteOnly(devNegNCC), *posNum, *negNum, numOfPatches); size_t globSize = 2 * numOfPatches*MAX_EXAMPLES_IN_MODEL; if (!k.run(1, &globSize, NULL, true)) printf("Kernel Run Error!!!"); Mat posNCC = devPosNCC.getMat(ACCESS_READ); Mat negNCC = devNegNCC.getMat(ACCESS_READ); //Calculate Srs for (int id = 0; id < numOfPatches; id++) { double spr = 0.0, smr = 0.0, spc = 0.0, smc = 0; int med = getMedian((*timeStampsPositive)); for (int i = 0; i < *posNum; i++) { spr = std::max(spr, 0.5 * (posNCC.at<float>(id * 500 + i) + 1.0)); if ((int)(*timeStampsPositive)[i] <= med) spc = std::max(spr, 0.5 * (posNCC.at<float>(id * 500 + i) + 1.0)); } for (int i = 0; i < *negNum; i++) smc = smr = std::max(smr, 0.5 * (negNCC.at<float>(id * 500 + i) + 1.0)); if (spr + smr == 0.0) resultSr[id] = 0.0; else resultSr[id] = spr / (smr + spr); if (spc + smc == 0.0) resultSc[id] = 0.0; else resultSc[id] = spc / (smc + spc); } }
void Graph::addSample(float sample) { noData = false; if(!buffer.empty() && (upSmoothing != 0 || downSmoothing != 0)) { if(sample > buffer.back()) { sample = ofLerp(sample, buffer.back(), upSmoothing); } else { sample = ofLerp(sample, buffer.back(), downSmoothing); } } if(minRange != 0 || maxRange != 0) { sample = ofClamp(sample, minRange, maxRange); } if(!buffer.empty()) { float diff = sample - buffer.back(); float cmp = bidirectional ? abs(diff) : diff; if(!derivative.empty() && derivative.back() < threshold && cmp > threshold) { lastTrigger = ofGetElapsedTimef(); triggered = true; } else { triggered = false; } derivative.push_back(abs(diff)); } buffer.push_back(sample); // could use a better datastructure to avoid resorting every sample float curThreshold = getMedian(derivative, percentile); if(threshold == 0 || threshold != threshold) { threshold = curThreshold; } else { threshold = ofLerp(curThreshold, threshold, thresholdSmoothing); } bufferPolyline = buildPolyline(buffer); derivativePolyline = buildPolyline(derivative); bufferBox = getBoundingBox(buffer); derivativeBox = getBoundingBox(derivative); if(minRange != 0 || maxRange != 0) { bufferBox.y = minRange; bufferBox.height = maxRange - minRange; buffer.back() = ofClamp(buffer.back(), minRange, maxRange); } if(bufferBox.height > FLT_EPSILON) { normalized = ofMap(buffer.back(), bufferBox.y, bufferBox.y + bufferBox.height, 0, 1); } if(derivative.size() > 0 && derivativeBox.height > FLT_EPSILON) { normalizedDerivative = ofMap(derivative.back(), derivativeBox.y, derivativeBox.y + derivativeBox.height, 0, 1); } activity = ofLerp(normalizedDerivative, activity, activitySmoothing); }
int main (void) { int arra[SIZE] = {1, 2, 9, 11, 13}; int arrb[SIZE] = {3, 4, 8, 10, 14}; int size = SIZE; int value ; value = getMedian(arra, arrb, 0, size - 1) ; if (-1 == value) value = getMedian(arrb, arra, 0, size - 1) ; printf ("%d\n", value); value = getMedian2(arra, arrb, 0, size - 1) ; printf ("%d\n", value); return 0 ; }
void computeBitmaps(InputArray _img, OutputArray _tb, OutputArray _eb) { Mat img = _img.getMat(); _tb.create(img.size(), CV_8U); _eb.create(img.size(), CV_8U); Mat tb = _tb.getMat(), eb = _eb.getMat(); int median = getMedian(img); compare(img, median, tb, CMP_GT); compare(abs(img - median), exclude_range, eb, CMP_GT); }
int main(){ int arr_1[10] = {1,3,10,5,4,8,12,5,6,7}; sort(arr_1, 10); std::cout << " "<< std::endl; print_array(arr_1,10); std::cout << " "<< std::endl; std::cout << "The Median is: " << getMedian(arr_1,10) << std::endl; std::cout << "The Mode is: " << getmode(arr_1, 10) << std::endl; }
// the kernel runs inside the image void kNearestNeighFilter::histogramMethodMiddle(const imatrix& src, imatrix& dest, ivector& histogram, const int& row,int& col) const { int i,j;//index int numOfMax, maxIndex; int max=0; const int maxChange = sizeOfKernel+1;//max change for "max" const int limit = sizeOfKernel/2; //half size of the kernel const int lastCol = src.lastColumn()-limit; const int r = row+limit; col = limit; int v; //del test while(col <= (lastCol-1)) { j = col-limit; // sub labels left form the kernel for(i=row-limit;i<=r;++i) { --histogram.at(src.at(i,j)); } // add labels right from the kernel ++col; j = col+limit; for(i=row-limit;i<=r;++i) { v = src.at(i,j); ++histogram.at(src.at(i,j)); } //get most(best) available label numOfMax = 0; maxIndex = -1; max -= maxChange; //=0; for(i=0;i<histoSize;++i) { if(histogram.at(i) < max);// for speed up (probability) else if(histogram.at(i) > max) { max = histogram.at(i); numOfMax = 1; maxIndex = i; } else //if(histogram.at(i) == max) ++numOfMax; } //is there more than one possibility ? if(numOfMax == 1) dest.at(row,col) = maxIndex; // is the kernel center one of the max's? else if(histogram.at(src.at(row,col)) == max) dest.at(row,col) = src.at(row,col); else dest.at(row,col) = getMedian(histogram,max,numOfMax); }//while };
medHeap medHeapSort ( medHeap H ) { int m; while (H.n1 + H.n2 > 0) { m = getMedian(H); H = delMedHeap(H); if (H.n1 == H.n2) H.val[H.capacity-1-H.n2] = m; /* Deletion in minheap */ else H.val[H.n1] = m; /* Deletion in maxheap */ } return H; }
/* Driver program to test above function */ int main() { int ar1[] = {1, 2, 3, 6}; int ar2[] = {4, 6, 8, 10}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf("Median is %d", getMedian(ar1, ar2, n1)); else printf("Doesn't work for arrays of unequal size"); return 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) { int m1; /* For median of ar1 */ int m2; /* For median of ar2 */ /* return -1 for invalid input */ if (n <= 0) return -1; if (n == 1) return (ar1[0] + ar2[0])/2; if (n == 2) return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2; m1 = median(ar1, n); /* get the median of the first array */ m2 = median(ar2, n); /* get the median of the second array */ /* If medians are equal then return either m1 or m2 */ if (m1 == m2) return m1; /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ if (m1 < m2) { if (n % 2 == 0) return getMedian(ar1 + n/2 - 1, ar2, n - n/2 +1); else return getMedian(ar1 + n/2, ar2, n - n/2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { if (n % 2 == 0) return getMedian(ar2 + n/2 - 1, ar1, n - n/2 + 1); else return getMedian(ar2 + n/2, ar1, n - n/2); } }
BinaryTree::BinaryTree(int sortedArray[], int length) { root = new Node(); root->data = getMedian(sortedArray,length); root->left = NULL; root->right = NULL; Node* currentNode = root; currentNode->left = createBTree(sortedArray,0,length/2 -1); currentNode->right = createBTree(sortedArray, length/2 +1, length-1); }
/* Driver program to test above function */ int main() { int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf("Median is %d", getMedian(ar1, ar2, n1)); else printf("Doesn't work for arrays of unequal size"); getchar(); return 0; }