Advertisement
heavenriver

2012_09_12.java (ex. 2)

Jan 10th, 2013
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. // Esame del 12 settembre 2012, esercizio 2
  2. // Ricordarsi di specificare sempre, nei commenti al codice, l'utilità di ogni metodo.
  3.  
  4. class RecursionNode has int[] config, RecursionNode left, RecursionNode right and methods addLeft and addRight;
  5. class RecursionTree has constructor public RecursionTree(int[] config); and method getRoot;
  6.  
  7. public static RecursionTree mergeSort(int[] a)
  8.     {
  9.     RecursionTree t = new RecursionTree(a);
  10.     mergeSort(a, t.getRoot());
  11.     return t;
  12.     }
  13.  
  14. public static int[] mergeSort(int[] a, RecursionNode n)
  15.     {
  16.     if(a.length <= 1) return a;
  17.     int[] b = new int[a.length / 2];
  18.     int[] c = new int[a.length / 2];
  19.     n.addLeftChild(b);
  20.     n.addRightChild(c);
  21.     b = mergeSort(b, n.left);
  22.     c = mergeSort(c, n.right);
  23.     return merge(b, c);
  24.     }
  25.  
  26. public static int[] merge(int[] b, int[] c)
  27.     {
  28.     int[] a = new int[b.length + c.length];
  29.     int leftIndex = 0;
  30.     int rightIndex = 0;
  31.     for(int i = 0; i < a.length; i++)
  32.         {
  33.         if(rightIndex >= c.length || b[leftIndex] <= c[rightIndex])
  34.             {
  35.             a[i] = b[leftIndex];
  36.             leftIndex++;
  37.             }
  38.         else
  39.             {
  40.             a[i] = c[rightIndex];
  41.             rightIndex++;
  42.             }
  43.         }
  44.     return a;
  45.     }
  46.  
  47. public void inorder()
  48.     {
  49.     inorder(root);
  50.     }
  51.  
  52. public void inorder(RecursionNode n)
  53.     {
  54.     if(n.hasLeft()) inorder(n.left());
  55.     System.out.println(n);
  56.     if(n.hasRight()) inorder(n.right());
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement