Advertisement
heret1c

Mergesort

Apr 26th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class MergeSort {
  4.    
  5.  
  6.     static final int[] sort(int[] input)
  7.     {
  8.         if(input.length > 1)
  9.         {
  10.             /*Mitte ausrechnen*/
  11.             int middle = (int)(input.length/2);
  12.            
  13.             /*Splitten*/
  14.             int[] left = new int[middle];
  15.             /*In das neue Array kopieren*/
  16.             for(int i = 0; i < left.length; i++)
  17.             {
  18.                 left[i] = input[i];
  19.             }
  20.             /*Splitten*/
  21.             int[] right = new int[input.length - middle];
  22.             /*In das neue Array kopieren*/
  23.             for(int i = middle; i < input.length; i++)
  24.             {
  25.                 right[i - middle] = input[i];
  26.             }
  27.             /*Die linke und rechte Hälfte sortieren (Das ist der Rekursiv-Schritt)*/
  28.             left = sort(left);
  29.             right = sort(right);
  30.             /*Wenn beide sortiert sind, sie mergen und damit auch sortieren*/
  31.             return merge(left,right);  
  32.         }
  33.         else
  34.         {
  35.             /*Wenn wir eine length von 1 haben brauchen wir nicht sortieren, und können einfach returnen.
  36.              * Hier ist der abbruch der rekursion*/
  37.             return input;
  38.         }
  39.     }
  40.    
  41.     static final int[] merge(int[] left, int[] right)
  42.     {
  43.         int[] ret = new int[left.length + right.length];
  44.         int i = 0;
  45.         int j = 0;
  46.         int index = 0;/*Das gleiche wie i + j*/
  47.         while(i < left.length && j < right.length)
  48.         {
  49.             if(left[i] < right[j])
  50.             {
  51.                 ret[index] = left[i];
  52.                 i++;
  53.             }
  54.             else
  55.             {
  56.                 ret[index] = right[j];
  57.                 j++;
  58.             }
  59.             index++;
  60.         }
  61.        
  62.         while( i < left.length)
  63.         {
  64.             ret[index] = left[i];
  65.             i++;
  66.             index++;
  67.         }
  68.         while( j < right.length)
  69.         {
  70.             ret[i + j] = right[j];
  71.             j++;
  72.             index++;
  73.         }
  74.        
  75.         return ret;
  76.     }
  77.    
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement