SHARE
TWEET

Aufgabe 3

a guest Oct 23rd, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MergeTwoSorted {
  2.     public static void mergeArrays(int[] fieldA, int[] fieldB, int[] fieldC) {
  3.         int i = 0, j = 0, k = 0;
  4.  
  5.         while (i < fieldA.length && j < fieldB.length) {
  6.             // prüft ob element aus A kleiner ist als B. Falls ja, es wird gepseichert
  7.             // und der Index von A wird vergroßert
  8.             // falls nein, dasselbe wird bei B probiert
  9.             if (fieldA[i] < fieldB[j])
  10.                 fieldC[k++] = fieldA[i++];
  11.             else
  12.                 fieldC[k++] = fieldB[j++];
  13.         }
  14.  
  15.         // den Rest der Elementen von A speichern
  16.         while (i < fieldA.length)
  17.             fieldC[k++] = fieldA[i++];
  18.  
  19.         // den Rest der Elementen von B speichern
  20.         while (j < fieldB.length)
  21.             fieldC[k++] = fieldB[j++];
  22.     }
  23.  
  24.     public static void main(String[] args) {
  25.         int[] fieldA = {1, 1, 3, 5, 7, 8, 9};
  26.         int[] fieldB = {2, 3, 4, 6, 8, 10};
  27.  
  28.         int fieldH = fieldA.length + fieldB.length;
  29.         int[] fieldC = new int[fieldH];
  30.  
  31.         mergeArrays(fieldA, fieldB, fieldC);
  32.  
  33.  
  34. // den Array wird für doppeleingaben geprüft
  35.         int current = fieldC[0];
  36.         boolean found = false;
  37.         for (int i = 0; i < fieldC.length; i++) {
  38.             if (current == fieldC[i] && !found) {
  39.                 found = true;
  40.             } else if (current != fieldC[i]) {
  41.                 System.out.print(" " + current);
  42.                 current = fieldC[i];
  43.                 found = false;
  44.             }
  45.         }
  46.         System.out.print(" " + current);
  47.     }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top