Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package algorithm;
- /**
- *
- * @author acer
- */
- public class mergeSort {
- public static int [] a={2,4,1,6,8,5,3,7};
- public static void main(String[] args) {
- mergeSort(a,0,a.length-1);
- System.out.println();
- print(a);
- }
- public static void mergeSort(int []a,int p,int r){
- if(p<r){
- int q=(p+r)/2;
- mergeSort(a,p,q);
- mergeSort(a,q+1,r);
- merge(a,p,q,r);
- }
- }
- public static void print(int [] arr){
- for(int n:arr){
- System.out.print(n+" ");
- }
- System.out.println();
- }
- public static void merge(int [] a,int p,int q, int r){
- int n1=q-p+1;
- int n2=r-q;
- int[]l=new int[n1+1];
- int [] ri=new int[n2+1];
- for(int i=0;i<n1;i++){
- l[i]=a[p+i];
- }
- for(int i=0;i<n2;i++){
- ri[i]=a[q+1+i];
- }
- System.out.println();
- print(l);
- print(ri);
- int i=0;
- int j=0;
- l[n1]=2222222;
- ri[n2]=2222222;
- for(int k=p;k<=r;k++){
- if(l[i]<=ri[j]){
- a[k]=l[i];
- i++;
- }
- else{
- a[k]=ri[j];
- j++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement