Advertisement
MilaDimitrovaa

Methods - MergeSort

Dec 18th, 2020
1,062
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package MergeSort183_02;
  2.  
  3. public class MergeSort_Methods {
  4.     public static void Divide(int []arr,int l ,int r) {
  5.  
  6.         if(l < r) {
  7.             int m = (l + r) / 2;
  8.  
  9.             Divide(arr,l,m); // Recursive Left;
  10.             Divide(arr, m + 1,r); //Recursive Left;
  11.  
  12.             CompareAndMergeArr(arr,l,m,r);
  13.  
  14.         }
  15.     }
  16.  
  17.  
  18.     private static void CompareAndMergeArr(int []arr,int l,int m,int r) {
  19.  
  20.         int LeftArrLenght = m - l + 1 ;
  21.         int RightArrLenght = r - m ;
  22.  
  23.         int [] L = new int [LeftArrLenght];
  24.         int [] R = new int [RightArrLenght];
  25.  
  26.         for (int i = 0; i < LeftArrLenght ; i++) {
  27.             L[i] = arr[l + i];
  28.         }
  29.         for (int j = 0; j < RightArrLenght; j++) {
  30.             R[j] = arr[m + 1 + j];
  31.         }
  32.  
  33.         int i = 0; // index for left array
  34.         int j = 0; // index for right array
  35.         int k = l;
  36.  
  37.         while( i < LeftArrLenght && j < RightArrLenght){
  38.  
  39.             if(L[i] <= R[j]){
  40.                 arr[k] = L[i];
  41.                 i++;
  42.             }
  43.             else{
  44.                 arr[k] = R[j];
  45.                 j++;
  46.             }
  47.             k++;
  48.  
  49.         }
  50.  
  51.         //Collect any elements from L and R if any
  52.  
  53.         while(i < LeftArrLenght){
  54.             arr[k]  = L[i];
  55.             i++;
  56.             k++;
  57.         }
  58.         while( j < RightArrLenght){
  59.             arr[k] = R[j];
  60.             j++;
  61.             k++;
  62.         }
  63.  
  64.  
  65.  
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement