Advertisement
Guest User

MergeSort

a guest
Mar 26th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. import java.util.Comparator;
  2.  
  3. public class MergeSort {
  4.  
  5.     private static final int CUTOFF = 7;
  6.  
  7.     static Comparable[] aux;
  8.     static Comparator c;
  9.  
  10.     private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
  11.         assert isSorted(a, lo, mid); // precondition: a[lo..mid] sorted
  12.         assert isSorted(a, mid + 1, hi); // precondition: a[mid+1..hi] sorted
  13.         for (int k = lo; k <= hi; k++)
  14.             aux[k] = a[k];
  15.         int i = lo, j = mid + 1;
  16.         for (int k = lo; k <= hi; k++) {
  17.             if (i > mid) a[k] = aux[j++];
  18.             else if (j > hi) a[k] = aux[i++];
  19.             else if (less(aux[j], aux[i])) a[k] = aux[j++];
  20.             else a[k] = aux[i++];
  21.         }
  22.         assert isSorted(a, lo, hi); // postcondition: a[lo..hi] sorted
  23.     }
  24.  
  25.     private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
  26.         if (hi <= lo) return;
  27.         if (hi <= lo + CUTOFF - 1) InsertionSort.sort(a, lo, hi, c);
  28.         else {
  29.             int mid = lo + (hi - lo) / 2;
  30.             sort(a, aux, lo, mid);
  31.             sort(a, aux, mid + 1, hi);
  32.             if (!less(a[mid + 1], a[mid])) return;
  33.             merge(a, aux, lo, mid, hi);
  34.         }
  35.     }
  36.  
  37.     public static void sort(Comparable[] a, Comparator x) {
  38.         c = x;
  39.         aux = new Comparable[a.length];
  40.         sort(a, aux, 0, a.length - 1);
  41.     }
  42.  
  43.     private static boolean isSorted(Comparable[] a, int l, int m) {
  44.         for (int i = l; i <= m; i++)
  45.             if (less(a[i], a[i - 1])) return false;
  46.         return true;
  47.     }
  48.  
  49.     private static boolean less(Object v, Object w) {
  50.         return c.compare(v, w) < 0;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement