Advertisement
FahimFaisal

MergeSort_main

Nov 2nd, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package algorithm;
  7.  
  8. /**
  9.  *
  10.  * @author acer
  11.  */
  12. public class mergeSort {
  13.    
  14.     public static int [] a={2,4,1,6,8,5,3,7};
  15.    
  16.     public static void main(String[] args) {
  17.        
  18.  
  19.        
  20.         mergeSort(a,0,a.length-1);
  21.         System.out.println();
  22.         print(a);
  23.        
  24.        
  25.     }
  26.     public static void mergeSort(int []a,int p,int r){
  27.     if(p<r){
  28.     int q=(p+r)/2;
  29.     mergeSort(a,p,q);
  30.     mergeSort(a,q+1,r);
  31.     merge(a,p,q,r);
  32.     }
  33.     }
  34.    
  35.     public static void print(int [] arr){
  36.          for(int n:arr){
  37.            System.out.print(n+" ");
  38.        }
  39.          System.out.println();
  40.     }
  41.    
  42.     public static void merge(int [] a,int p,int q, int r){
  43.        
  44.         int n1=q-p+1;
  45.         int n2=r-q;
  46.        
  47.         int[]l=new int[n1+1];
  48.         int [] ri=new int[n2+1];
  49.        
  50.          for(int i=0;i<n1;i++){
  51.             l[i]=a[p+i];    
  52.         }
  53.  
  54.         for(int i=0;i<n2;i++){
  55.             ri[i]=a[q+1+i];
  56.          
  57.         }
  58.         System.out.println();
  59.        
  60.         print(l);
  61.        
  62.         print(ri);
  63.        
  64.        
  65.         int i=0;
  66.         int j=0;
  67.      
  68.         l[n1]=2222222;
  69.         ri[n2]=2222222;
  70.        
  71.     for(int k=p;k<=r;k++){
  72.          
  73.            if(l[i]<=ri[j]){
  74.                a[k]=l[i];
  75.                i++;
  76.              
  77.            }
  78.            else{
  79.                a[k]=ri[j];
  80.                j++;
  81.                
  82.            }
  83.            
  84.        }
  85.        
  86.        
  87.        
  88.    
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement