Guest User

Untitled

a guest
Aug 20th, 2018
2,176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. import java.util.List;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4.  
  5. public class Merge {
  6.  public static <E extends Comparable<? super E>> List<E> mergeSort(List<E> m) {
  7.   if(m.size() <= 1) return m;
  8.  
  9.   int middle = m.size() / 2;
  10.   List<E> left = m.subList(0, middle);
  11.   List<E> right = m.subList(middle, m.size());
  12.  
  13.   right = mergeSort(right);
  14.   left = mergeSort(left);
  15.   List<E> result = merge(left, right);
  16.  
  17.   return result;
  18.  }
  19.  
  20.  public static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right) {
  21.   List<E> result = new ArrayList<E>();
  22.   Iterator<E> it1 = left.iterator();
  23.   Iterator<E> it2 = right.iterator();
  24.  
  25.   E x = it1.next();
  26.   E y = it2.next();
  27.   while (true) {
  28.     //change the direction of this comparison to change the direction of the sort
  29.     if(x.compareTo(y) <= 0) {
  30.        result.add(x);
  31.        if(it1.hasNext()) {
  32.             x = it1.next();
  33.        } else {
  34.             result.add(y);
  35.             while(it2.hasNext()) {
  36.                     result.add(it2.next());
  37.             }
  38.             break;
  39.        }
  40.  } else {
  41.        result.add(y);
  42.        if(it2.hasNext()) {
  43.        y = it2.next();
  44.        } else {
  45.             result.add(x);
  46.             while (it1.hasNext()) {
  47.                     result.add(it1.next());
  48.             }
  49.             break;
  50.        }
  51.     }
  52.   }
  53.   return result;
  54.  }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment