double findMedian(int * A1, int b1,int e1,int * A2,int b2,int e2){ if (b1 >= e1) return findMedian(A2,b2,e2); if (b2 >= e2) return findMedian(A1,b1,e1); if (e1 - b1 > e2 -b2) return findMedian(A2,b2,e2,A1,b1,e1); int m11 = (b1+e1-1)/2, m12 = (b1+e1)/2; int m21 = (b2+e2-1)/2, m22 = (b2+e2)/2; if (e1 == b1+1) { if (e2 == b2+1) return (A1[b1] + A2[b2])/2.0; if ((e2 -b2) % 2 == 0) { if (A1[b1] < A2[m21]) return A2[m21]; if (A1[b1] > A2[m22]) return A2[m22]; return A1[b1]; } else { if (A1[b1] < A2[m21 -1]) return (A2[m21-1] + A2[m21])/2.0; if (A1[b1] > A2[m22 +1]) return (A2[m21] + A2[m21+1])/2.0; return (A1[b1]+ A2[m21]) / 2.0; } } int deta = 0; if ((e1- b1)%2==0) deta = (m11-b1+1); else deta = (m11 -b1); if (A1[m11] > A2[m21]) b2 += deta; else b1 += deta; if (A1[m12] < A2[m22]) e2 -= deta; else e1 -= deta; return findMedian(A1,b1,e1,A2,b2,e2); }
int findMedian(int A[], int m, int B[], int n, int k) { if(m == 0) return B[k-1]; if(n == 0) return A[k-1]; int i = m >> 1, j = n >> 1, *p, *q, t; if(A[i] < B[j]) { p = A; q = B; } else { p = B; q = A; swap(i, j); swap(m, n); } t = i + j + 1; if(t >= k) return findMedian(p, m, q, j, k); else { return findMedian(p+i+1, m-i-1, q, n, k-i-1); } }
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len1 = nums1.size(); int len2 = nums2.size(); if (len1 == 0 && len2 == 0) { return 0; } int medianIndex1L = -1; int medianIndex1R = -1; int medianIndex2L = -1; int medianIndex2R = -1; if (len1 == 0 || len2 == 0) { return len2 == 0 ? findMedian(nums1, 0, len1 - 1, medianIndex1L, medianIndex1R) : findMedian(nums2, 0, len2 - 1, medianIndex2L, medianIndex2R); } int start1 = 0; int end1 = len1 - 1; int start2 = 0; int end2 = len2 - 1; double m1; double m2; do { m1 = findMedian(nums1, start1, end1, medianIndex1L, medianIndex1R); m2 = findMedian(nums2, start2, end2, medianIndex2L, medianIndex2R); if (m1 == m2) { return m1; } else if (m1 < m2) { start1 = medianIndex1L; end2 = medianIndex2R; } else { start2 = medianIndex2L; end1 = medianIndex1R; } } while (start1 <= end1 && start2 <= end2); double m; if (start1 > end1 && start2 > end2) { if (nums1[len1 - 1] <= nums2[0]) { m = (double)(nums1[len1 - 1] + nums2[0]) / 2.0; } else { m = (double)(nums1[0] + nums2[len2-1]) / 2.0; } } else if (start1 > end1) { m = findMedian(nums2, start2, end2, medianIndex2L, medianIndex2R); } else { m = findMedian(nums1, start1, end1, medianIndex1L, medianIndex1R); } return m; }
double findMedianSortedArrays(int A[], int m, int B[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int k = m + n; double res = 0.0 + findMedian(A, m, B, n, k/2+1); if(k % 2 == 0) res = (res + findMedian(A, m, B, n, k/2))/2; return res; }
int main() { // Your MedianFinder object will be instantiated and called as such: struct MedianFinder* mf = MedianFinderCreate(); addNum(mf, 2); printf("\n median=%lf",findMedian(mf)); addNum(mf,3); printf("\n median=%lf",findMedian(mf)); MedianFinderFree(mf); }
int main() { double list1[5] = {4, 5, 7, 9, 11}; double list2[1] = {5}; double list3[6] = {10, 8, 6, 4, 2, 0}; std::cout << "list1 median: " << findMedian(list1, 5) << std::endl; std::cout << "list2 median: " << findMedian(list2, 1) << std::endl; std::cout << "list3 median: " << findMedian(list3, 6) << std::endl; return 0; }
int main(){ double first = 12.0; //, second = 99.33; /* TO DO: This is where you initialize your house prices array. * The rest of the values will default to 0.0 if you do not provide enough * values to fill the entire array */ int numberOfHomes = 71; // change this value here and on the next line. // C does not like you to initialize a variable-sized array. double houses[71] = {129500.0, 129900.0, 138900.0, 159900.0, 44900.0, 490000.0, 89500.0, 34000.0, 82000.0, 219900.0, 47500.0, 144900.0, 159999.0, 99900.0, 166900.0, 229900.0, 240000.0, 89900.0, 299900.0, 49900.0, 585000.0, 275000.0, 209900.0, 259900.0, 269900.0, 389900.0, 86500.0, 99900.0, 79900.0, 175000.0, 54900.0, 139900.0, 129900.0, 34900.0, 119900.0, 257700.0, 149900.0, 139900.0, 149900.0, 174900.0, 145900.0, 189900.0, 212900.0, 48900.0, 75900.0, 330000.0, 17500.0, 235000.0, 449900.0, 179900.0, 119900.0, 147000.0, 155000.0, 239000.0, 219900.0, 309000.0, 131900.0, 345000.0, 165000.0, 299900.0, 45000.0, 230000.0, 99500.0, 83500.0, 156900.0, 289900.0, 45900.0, 185500.0, 19000.0, 124000.0, 159900.0}; //testSwap(&first, &houses[2]); sort(houses, numberOfHomes); //printArray(&houses[0], numberOfHomes); double mean, median; mean = findMean(houses, numberOfHomes); median = findMedian(houses, numberOfHomes); printf("The mean price of 4 bedroom houses in Vigo County is $%2.1lf\n", mean); printf("The median price of 4 bedroom houses in Vigo Country is $%2.1lf\n", median); printNHighestPrices(houses, 10, 5); printNlowestPrices(houses, 10, 5); //int a[3] = {4}, b[] = {4}; //printf ("Array equality: %d\n", a == b); return 0; }
int minMoves2(vector<int>& nums) { int ret = 0, median = findMedian(nums); // median = *nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end()); for (auto num : nums) ret += abs(num - median); return ret; }
int main() { srand((unsigned int)time(NULL)); int n,*H,N1=0,N2=0,M; int i=0,x; printf("n="); scanf("%d",&n); H=(int *)malloc(n*sizeof(int)); printf("\n\n+++ MedHeap initialized"); printf("\n\n+++ Going to insert elements one by one in MedHeap"); for(i=0;i<n;i++) { x=rand()%30000; printf("\nInsert(%d) done.",x); insertMed(H,n,N1,N2,x); M=findMedian(H,n,N1,N2); printf("Current Median=%d.",M); } MedHeapSort(H,n,N1,N2); printf("\n+++ Median Heap Sort done\n"); for(i=0;i<n;i++) printf("%d ",H[i]); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { struct node *head = create(NULL); printf("Median: %d\n", findMedian(head)); getch(); return 0; }
// Calculate zero for all 3 axis, storing it for later measurements // This assumes your platform is truly level! // See also: http://www.freescale.com/files/sensors/doc/app_note/AN3447.pdf void Accel::autoZero(){ // Take 50 measurements of all 3 axis, find the median, that's our zero-point // Why 50? Because that's what the aeroquad project does byte loopCount = 50; //Serial.print("Starting accel autoZero with "); //Serial.print(loopCount, DEC); //Serial.println(" iterations."); int findZero[loopCount]; for (byte axis = XAXIS; axis <= ZAXIS; axis++){ for (byte i=0; i<loopCount; i++){ sendReadRequest(0x32 + (axis * 2)); findZero[i] = readWordFlip(); delay(10); } zero[axis] = findMedian(findZero, loopCount); /*Serial.print("Zero of accel axis "); Serial.print(axis, DEC); Serial.print(" is: "); Serial.println(zero[axis]);*/ } // Write to eeprom // eeprom_write(EEPROM_ADDR_ACCEL_PITCH, zero[XAXIS]); // eeprom_write(EEPROM_ADDR_ACCEL_ROLL, zero[YAXIS]); // eeprom_write(EEPROM_ADDR_ACCEL_YAW, zero[ZAXIS]); }
void tester(int n) { int i; for (i = 0; i < n; i++) if (findMedian(createList(cases[i].list, cases[i].n)) == cases[i].r) printf("PASS\n"); else printf("FAIL\n"); }
// Median of medians algorithm: find k th smallest number in the sub-array[l..r] int medianOfMedians(int *arr, const int &l, const int &r, const int &k) { int n = r - l + 1; // length of the sub array // if k is out of range, throw exception if (k <= 0 || k > n) throw std::invalid_argument("invalid k-th"); // divide sub-arrary[l..r] in groups of size GROUP_NUM (the last group length can be less than GROUP_NUM) // calculate median of each groups and store them in median array int const medianNum = static_cast<int>(ceil(static_cast<double>(n) / static_cast<double>(GROUP_NUM))); //int const medianNum = (n + 4) / GROUP_NUM; int median[medianNum]; int median_i; for (median_i = 0; median_i < n / GROUP_NUM; ++median_i) median[median_i] = findMedian(arr + l + median_i * GROUP_NUM, GROUP_NUM); if (median_i * GROUP_NUM < n) { // last group with elements less than GROUP_NUM median[median_i] = findMedian(arr + l + median_i * GROUP_NUM, n % GROUP_NUM); } // Find median of all medians recursively int medOfMedians; if (medianNum == 1) // first median is the median of medians since there's only one median medOfMedians = median[0]; else { // we don't need to consider odd and even array length cases, // since this median is used for partition medOfMedians = medianOfMedians(median, 0, medianNum - 1, medianNum / 2); } // get the medOfMedians's index int pivot_i; for (pivot_i = l; pivot_i < r; ++pivot_i) { if (arr[pivot_i] == medOfMedians) break; } // partition the array around median of medians int pos = partition(arr, l, r, pivot_i); if (pos - l + 1 == k) // if the pos is the kth number, return it return arr[pos]; if (pos - l + 1 > k) // if position is more than kth, find kth within left sub-array return medianOfMedians(arr, l, pos - 1, k); else // if position is less than kth, find kth within right sub-array return medianOfMedians(arr, pos + 1, r, k - pos + l - 1); }
double findMedian(int A[], int m, int B[], int n, int l, int r) { if (l > r) return findMedian(B, n, A, m, max(0, (m + n) / 2 - m), min(n, (m + n) / 2)); int i = (l + r) / 2; int j = (m + n) / 2 - i; int Ai_1 = (i == 0) ? INT_MIN : A[i-1]; int Bj_1 = (j == 0) ? INT_MIN : B[j-1]; int Ai = (i == m) ? INT_MAX : A[i]; int Bj = (j == n) ? INT_MAX : B[j]; if (Ai < Bj_1) return findMedian(A, m, B, n, i+1, r); if (Ai > Bj) return findMedian(A, m, B, n, l, i-1); if ((m + n) % 2 == 1) return Ai; else return (Ai + max(Ai_1, Bj_1)) / 2.0; }
void MedHeapSort(int *H,int n,int& N1,int& N2) // function sorts the elements of the the medHeap in O(nlogn) { int i=n; while(i>0) { int m=findMedian(H,n,N1,N2); deleteMed(H,n,N1,N2); if(N1==N2){H[n-N2-1]=m;} else {H[N1]=m;} i--; } }
double Sensor::findTrimmed(double arr[], double percent) { double median = findMedian(arr); double trim = NUM_OF_DATA * (percent / 100.0); for (int i = 0; i < trim; i++) { arr[i] = median; arr[(NUM_OF_DATA - i) - 1] = median; } /////////////////////////////////test // Serial.print("trimmed\n"); // testingArray(arr); //////////////////////////////// return findMean(arr); }
//============================================================================== double PitchDetector::detectPitch (float* samples, int numSamples) noexcept { Array<double> pitches; pitches.ensureStorageAllocated (int (numSamples / numSamplesNeededForDetection)); while (numSamples >= numSamplesNeededForDetection) { double pitch = detectPitchForBlock (samples, numSamplesNeededForDetection);//0.0; if (pitch > 0.0) pitches.add (pitch); numSamples -= numSamplesNeededForDetection; samples += numSamplesNeededForDetection; } if (pitches.size() == 1) { return pitches[0]; } else if (pitches.size() > 1) { DefaultElementComparator<double> sorter; pitches.sort (sorter); const double stdDev = findStandardDeviation (pitches.getRawDataPointer(), pitches.size()); const double medianSample = findMedian (pitches.getRawDataPointer(), pitches.size()); const double lowerLimit = medianSample - stdDev; const double upperLimit = medianSample + stdDev; Array<double> correctedPitches; correctedPitches.ensureStorageAllocated (pitches.size()); for (int i = 0; i < pitches.size(); ++i) { const double pitch = pitches.getUnchecked (i); if (pitch >= lowerLimit && pitch <= upperLimit) correctedPitches.add (pitch); } const double finalPitch = findMean (correctedPitches.getRawDataPointer(), correctedPitches.size()); return finalPitch; } return 0.0; }
int main() { int n=200000,H[200000],N1=0,N2=0,M; int i=0,x; char s[1000]; scanf("%s",s); while(s[0]!='E') { if(s[0]=='A'){scanf("%d",&x);insertMed(H,n,N1,N2,x);} if(s[0]=='M'){printf("%d\n",findMedian(H,n,N1,N2));} scanf("%s",s); } return 0; }
// // update the m_globalMedian vector when each region is created // bool CCSRegion::updateGlobalMedians(CCSIntArray& globalMedians, CCSAssemblyFileMgr* pAssemblyFileMgr) { int cnt = -1; CString pFeatureStr; for (int i = 0; i < globalMedians.GetSize(); ++i) { pFeatureStr = pAssemblyFileMgr->m_globalFeatures.GetAt(i).GetString(); if (!m_featureCounts.Lookup(pFeatureStr, cnt)) // if a region has a feature with value X, incremet X in redundancyVetor ++ pAssemblyFileMgr->m_redundancyVector[i][0]; // this region does not have such feature, so just increase 0 (X = 0) else { if (cnt > 100 ) { tcout << _T("CCSAssemblyFileMgr::constructRedundancyVector: incorrect vector size. increment the size to more than 100") << endl; ASSERT(false); return false; } ++ pAssemblyFileMgr->m_redundancyVector[i][cnt]; // this region has such feature, so incerase X (X = cnt) } globalMedians.GetAt(i) = findMedian(pAssemblyFileMgr->m_redundancyVector[i]); // find the median of this feature and update m_globalMedians } return true; }
void insertMed(int *H,int n,int& N1,int& N2,int x) // inserts an element in the med heap { int m=findMedian(H,n,N1,N2); if(m==-1){H[n-1]=x;N2++;return;} if(x<=m) { if(N2==N1+1)insertMax(H,N1,x); else { int max=findMax(H,N1);deleteMax(H,N1); insertMin(H+n-N2,N2,max);insertMax(H,N1,x); } } else { if(N2==N1)insertMin(H+n-N2,N2,x); else { int min=findMin(H+n-N2,N2);deleteMin(H+n-N2,N2); insertMax(H,N1,min);insertMin(H+n-N2,N2,x); } } }
double findMedianSortedArrays(int A[], int m, int B[], int n) { return findMedian(A,0,m,B,0,n); }
//ex double findMedianSortedArrays3(int A[], int m, int B[], int n) { return findMedian(A, m, B, n, max(0, (m + n) / 2 - n), min(m - 1, (m + n) / 2)); }