Manioc

merge

May 3rd, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. package sorting.divideAndConquer;
  2.  
  3. import sorting.AbstractSorting;
  4.  
  5. /**
  6.  * Merge sort is based on the divide-and-conquer paradigm. The algorithm
  7.  * consists of recursively dividing the unsorted list in the middle, sorting
  8.  * each sublist, and then merging them into one single sorted list. Notice that
  9.  * if the list has length == 1, it is already sorted.
  10.  */
  11. public class MergeSort<T extends Comparable<T>> extends AbstractSorting<T> {
  12.  
  13.     @Override
  14.     public void sort(T[] array, int leftIndex, int rightIndex) {
  15.         if(leftIndex >= 0 && rightIndex < array.length && leftIndex < array.length && rightIndex >= 0 && leftIndex != rightIndex) {
  16.    
  17.             T aux[] = (T[]) new Comparable[leftIndex + rightIndex + 7];
  18.             int mid = (leftIndex + rightIndex)/2;
  19.             sort(array, leftIndex, mid);
  20.             sort(array, mid+1, rightIndex);
  21.            
  22.             int i = leftIndex, j = mid+1, x = 0;
  23.             for(;i <= mid && j <= rightIndex; x++) {
  24.                 if(array[i].compareTo(array[j]) <= 0) {
  25.                     aux[x] = array[i++];
  26.                 }else {
  27.                     aux[x] = array[j++];
  28.                 }
  29.             }
  30.            
  31.            
  32.             while(i <= mid) {
  33.                 aux[x++] = array[i++];
  34.             }
  35.            
  36.             while(j <= rightIndex) {
  37.                 aux[x++] = array[j++];
  38.             }
  39.            
  40.             for(i = leftIndex, j = 0; i <= rightIndex; i++, j++) array[i] = aux[j];
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment