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 cse221;
- /**
- *
- * @author acer
- */
- public class MergeSortAlgorithm {
- 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();
- for(int i:a){
- System.out.print(i+",");
- }
- }
- public static void mergeSort(int [] a,int p,int r){
- if(p<r){
- int q=(int)Math.floor((p+r)/2);
- mergeSort(a,p,q);
- mergeSort(a,q+1,r);
- merge(a,p,q,r);
- }
- }
- 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 []R=new int [n2+1];
- for(int i=0;i<n1;i++){
- L[i]=a[p+i];
- }
- for(int j=0;j<n2;j++){
- R[j]=a[q+j+1];
- }
- L[n1]=7777;
- R[n2]=7777;
- int i=0;
- int j=0;
- for(int k=p;k<=r;k++){
- if(L[i]<R[j]){
- a[k]=L[i];
- i++;
- }
- else{
- a[k]=R[j];
- j++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment