MERGE_SORT in java

import java.util.*;



class msort
{


 public static void main(String args[])
 {
Scanner s=new Scanner(System.in);
int n=s.nextInt();

        int a[]=new int [n];

for(int i=0;i<n;i++)
a[i]=s.nextInt();

merge_sort(a,0,n-1);

for(int i=0;i<n;i++)
System.out.print(a[i]+" ");

 }

  static void merge_sort(int a[],int st,int en)
  {
 if(st<en)
 {
       int k=(st+en)/2;
  merge_sort(a,st,k);
  merge_sort(a,k+1,en);
  merge(a,st,k,en);
 }
  }
 
    static void merge(int array[],int lowerIndex,int middle,int higherIndex)
{
int tempMergArr[]=new int[higherIndex-lowerIndex+1];

int k=0;
       for (int i = lowerIndex; i <= higherIndex; i++)
            tempMergArr[k++] = array[i];

        int i = lowerIndex;
int r=i;
        int j = middle + 1;
         k = lowerIndex;

        while (i <= middle && j <= higherIndex)
{
            if (tempMergArr[i-r] <= tempMergArr[j-r]) {
                array[k] = tempMergArr[i-r];
                i++;
            } else {
                array[k] = tempMergArr[j-r];
                j++;
            }
            k++;
        }


        while (i <=middle) {
            array[k] = tempMergArr[i-r];
            k++;
            i++;
        }

 while (j <=higherIndex) {
            array[k] = tempMergArr[j-r];
            k++;
            j++;
        }

    }
}

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.