Last active
June 10, 2021 13:14
-
-
Save tbelmega/2d1c1f1827454d0f74160f07d565646b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class MergeDemo { | |
public static void main(String[] args) { | |
// Testfälle und Ausgaben. Von trivial über einfach bis schwer | |
System.out.println(Arrays.toString(m(new double[]{}, new double[]{})) + " erwartet: leer"); | |
System.out.println(Arrays.toString(m(new double[]{0}, new double[]{0})) + " erwartet: 0 0"); | |
System.out.println(Arrays.toString(m(new double[]{0}, new double[]{1})) + " erwartet: 1 0"); | |
System.out.println(Arrays.toString(m(new double[]{1}, new double[]{0})) + " erwartet: 1 0"); | |
System.out.println(Arrays.toString(m(new double[]{2, 1}, new double[]{1})) + " erwartet: 2 1 1"); | |
System.out.println(Arrays.toString(m(new double[]{10, 5, 1}, new double[]{6,4,3})) + " erwartet: 10,6,5,4,3,1"); | |
System.out.println(Arrays.toString(m(new double[]{10, 9, 8}, new double[]{3, 2, 1})) + " erwartet: 10,9,8,3,2,1"); | |
} | |
// Gedankengang: | |
// 1) Schleife, um result[] zu befüllen | |
// 2) Typische Schleife über die Eingabearrays geht nicht. Brauchen unabhängige Zeiger für X und Y, da pro Schleifendurchlauf nur einer von beiden hochzählt | |
// 3) Whileschleife und (nextX + nextY) als Zähler für result[] (Gedanke verworfen, For-Schleife über Resultarray ist einfacher) | |
// 4) Testcode in main mit ganz einfachen Fällen, zunehmend schwieriger | |
// 5) ArrayIndexOutOfBoundsException -> Scharfes Nachdenken oder Debuggen | |
public static double[] m(double[] arrayX, double[] arrayY) { | |
double[] result = new double[arrayX.length + arrayY.length]; | |
int nextXIndex = 0; | |
int nextYIndex = 0; | |
for (int i = 0; i < result.length; i++) { | |
// Falls x schon "aufgebraucht", nimm immer y | |
if (nextXIndex >= arrayX.length) { | |
result[i] = arrayY[nextYIndex]; | |
nextYIndex++; | |
// Falls y schon "aufgebraucht", nimm immer x | |
} else if (nextYIndex >= arrayY.length) { | |
result[i] = arrayX[nextXIndex]; | |
nextXIndex++; | |
// sonst nimm immer das größere von beiden | |
} else if (arrayX[nextXIndex] > arrayY[nextYIndex]) { | |
result[i] = arrayX[nextXIndex]; | |
nextXIndex++; | |
} else { | |
result[i] = arrayY[nextYIndex]; | |
nextYIndex++; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment