Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. package sorting;
  2.  
  3. import java.util.Comparator;
  4.  
  5. public class MergeSort extends Sort {
  6.     public static <E> void Sort(E[] array, Comparator<E> c) {
  7.         sort(array, 0, array.length - 1, c, (E[]) new Object[array.length]);
  8.  
  9.     }
  10.  
  11.     private static <E> void sort(E[] array, int i, int j, Comparator<E> c,
  12.             E[] aux) {
  13.         if (i == j)
  14.             return;
  15.         sort(array, i, (i + j) / 2, c, aux);
  16.         sort(array, (i + j) / 2+1, j, c, aux);
  17.         merge(array, i, (i + j) / 2 , (i + j) / 2+1, j, c, aux);
  18.     }
  19.  
  20.     private static <E> void merge(E[] array, int s1, int e1, int s2, int e2,
  21.             Comparator<E> c, E[] aux) {
  22.         int i=s1;
  23.         int j=s2;
  24.         int x=0;
  25.         while(i<=e1&&j<=e2)
  26.         {
  27.             if(less(array[i],array[j],c))
  28.             {
  29.                 aux[x++]=array[i++];
  30.             }else{
  31.                 aux[x++]=array[j++];
  32.             }
  33.         }
  34.         while(i<=e1)
  35.         {
  36.             aux[x++]=array[i++];
  37.         }
  38.         while(j<=e2)
  39.         {
  40.             aux[x++]=array[j++];
  41.         }
  42.        
  43.         for(x=0;x<=j-i;x++)
  44.             array[s1++]=aux[x];
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement