daily pastebin goal
84%
SHARE
TWEET

Untitled

a guest Feb 15th, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class MergeSort {
  2.     public static int[] merge(int[] array) {
  3.         if(array.length == 1)
  4.             return array;
  5.        
  6.         int lengthHalf = array.length / 2;
  7.         int[] leftArray = new int[lengthHalf];
  8.         int[] rightArray = new int[array.length - lengthHalf];
  9.        
  10.         for(int j = 0; j < rightArray.length; j++) {
  11.             rightArray[j] = array[j + leftArray.length];
  12.         }
  13.        
  14.         leftArray = merge(leftArray);
  15.         rightArray = merge(rightArray);
  16.        
  17.         int leftIndex = 0;
  18.         int rightIndex = 0;
  19.        
  20.         for(int k = 0; k < array.length; k++) {
  21.             if(rightIndex >= rightArray.length || (leftIndex < leftArray.length && leftArray[leftIndex] < rightArray[rightIndex])) {
  22.                 array[k] = leftArray[leftIndex];
  23.                 leftIndex++;
  24.             } else {
  25.                 array[k] = rightArray[rightIndex];
  26.                 rightIndex++;
  27.             }
  28.         }
  29.        
  30.         return array;
  31.     }
  32. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top