FahimFaisal

MergeSortAlgorithm_Faculty

Jan 28th, 2020
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 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 cse221;
  7.  
  8. /**
  9.  *
  10.  * @author acer
  11.  */
  12. public class MergeSortAlgorithm {
  13.     public static int [] a={2,4,1,6,8,5,3,7};
  14.    
  15.     public static void main(String[] args) {
  16.        
  17.  
  18.        
  19.         mergeSort(a,0,a.length-1);
  20.         System.out.println();
  21.         for(int i:a){
  22.             System.out.print(i+",");
  23.         }
  24.        
  25.        
  26.     }
  27.     public  static void mergeSort(int [] a,int p,int r){
  28.         if(p<r){
  29.             int q=(int)Math.floor((p+r)/2);
  30.             mergeSort(a,p,q);
  31.             mergeSort(a,q+1,r);
  32.             merge(a,p,q,r);
  33.         }
  34.     }
  35.    
  36.     public static void merge(int []a,int p,int q,int r){
  37.         int n1=q-p+1;
  38.         int n2=r-q;
  39.         int []L=new int[n1+1];
  40.         int []R=new int [n2+1];
  41.        
  42.         for(int i=0;i<n1;i++){
  43.             L[i]=a[p+i];
  44.         }
  45.         for(int j=0;j<n2;j++){
  46.             R[j]=a[q+j+1];
  47.         }
  48.         L[n1]=7777;
  49.         R[n2]=7777;
  50.        
  51.         int i=0;
  52.         int j=0;
  53.        
  54.         for(int k=p;k<=r;k++){
  55.             if(L[i]<R[j]){
  56.                 a[k]=L[i];
  57.                 i++;
  58.               }
  59.             else{
  60.                 a[k]=R[j];
  61.                 j++;
  62.             }
  63.            
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment