J'essaie de trouver la médiane de deux rangées triées de tailles différentes. Mais il y a quelques situations où cela ne fonctionne pas et je n'ai pas pu comprendre pourquoi. J'ai inclus ma mise en œuvre ci-dessous. Je suis conscient qu'il existe des solutions similaires en ligne. Mais je commence juste à apprendre des algorithmes et je veux en faire autant que possible par moi-même. Merci beaucoup d'avance pour votre aide!Médiane de deux rangées triées de tailles différentes
public double median(Point[] arr, int start, int end) {
int n = end - start + 1;
if (n % 2 == 0) {
return (double) (arr[start + (n/2)].getSz() + arr[start + (n/2) - 1].getSz())/2;
}
else {
return (double) arr[start + (n/2)].getSz();
}
}
public double getMedian(int aStart, int aEnd, int bStart, int bEnd) {
int m = aEnd - aStart + 1;
int n = bEnd - bStart + 1;
double median = 0;
if (m == 0 && n > 0) {
return median(arr2, 0, bEnd);
}
if (m > 0 && n == 0) {
return median(arr1, 0, aEnd);
}
if (m == 1 && n == 1) {
return (double) (arr1[0].getSz() + arr2[0].getSz())/2;
}
if (m == 2 && n == 2) {
median = (double) (Math.max(arr1[aStart].getSz(), arr2[bStart].getSz()) + Math.min(arr1[aEnd].getSz(), arr2[bEnd].getSz()))/2;
return median;
}
double m1 = median(arr1, aStart, aEnd);
double m2 = median(arr2, bStart, bEnd);
if (m1 == m2) {
return m1;
}
if (m1 < m2) {
if (m % 2 == 0) {
aStart = aStart + (m/2) - 1;
index = 1;
}
else {
index = 2;
aStart = aStart + m/2;
}
bEnd = bStart + n/2;
}
else {
if (n % 2 == 0) {
index = 3;
bStart = bStart + n/2 - 1;
}
else {
index = 4;
bStart = bStart + n/2;
}
aEnd = aStart + m/2;
}
return (getMedian(aStart, aEnd, bStart, bEnd));
}
Voici un exemple pour lequel les pauses logiques:
arr1 = 6, 20, 28, 29, 36, 41
arr2 = 14, 25, 33, 47, 53, 66, 79, 98
correcte médiane = 34,5
médiane estimée = 31
Oui, cela aide beaucoup! Fonctionne parfaitement maintenant. Merci beaucoup. – sh1291