Pages

Saturday, 4 January 2020

Merge sort using this keyword and copyOf method

// Merge sort using this keyword and copyOf method

import java.util.*;
class Rkms
{
    int[] a;
    int[] tmpa;
    int length;
    public static void main(String args[])
      {
        int[] ia = {38,27,43,3,9,82,10};
       
        Rkms ms=new Rkms();
   
    System.out.printf("\n unsorted array :");
        for (int i: ia)
            System.out.print(i +" ");
             
        ms.sort(ia);

        System.out.printf("\n sorted array :");
        for (int i :ia)
            System.out.print(i +" ");
       }
 
    public void sort(int ia[])
        {
          this.a=ia;
      this.length=ia.length;
      this.tmpa=new int[length];
      divideArray(0,length-1);
    }
   
    public void divideArray(int p,int r)
        {
          if(p<r)
           {
            // Find the middle point
            int q =(p+r)/2;
               System.out.printf("\n\t first and second array element :");
        int[] FS = Arrays.copyOf(a,r+1);
            for (int i=0; i<FS.length; i++)
            System.out.print(FS[i]+" ");
                    
        // Sort first and second halves
            divideArray(p,q);
       
            divideArray(q+1,r);
          
        // Merge the sorted halves
            mergeArray( p, q, r);
            System.out.printf("\n merged array element :");
            int[] F = Arrays.copyOf(a,r+1);
            for (int k=0; k<F.length; k++)
            System.out.print(F[k]+" ");

        }
        }

    public void mergeArray(int p, int q, int r)
    {
        for (int i=p;i<=r;i++)
        {
     tmpa[i]=a[i];
    }
    int i=p;
    int j=q+1;
    int k=p;
        while (i <= q && j<=r)
        {
       a[k++]=(tmpa[i]<=tmpa[j]) ? tmpa[i++]: tmpa[j++];
        }

    while(i<=q)
    {
    a[k]=tmpa[i];
    k++;
    i++;
    }
    }
}

output:

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...