Merge Sort

Merge two sorted array into a third array

class name : MergeSort
Data members
x[] – integer array
n – size of the array
Functions
Constructor
void accept() – accept the size and the array elements for Object A, B and C
void display() – display the arrays
void bSort() – function that uses bubble sort method to sort object A
void sSort () – function that uses selection sort method to sort object B
MergeSort merge(MergeSort B) return the sorted merged array
write the main function create objects and accepts two arrays, sort them and merge them to get a sorted array

import java.util.Scanner;
public class MergeSort
{
  int x[];
  int n;
  MergeSort(int nn)
  {
      n=nn;
      x=new int[n];
  }
  MergeSort()
  {
  }
  void bSort()
  {
      boolean flag=true;  
      while (flag)
        {
            int j,temp;
            flag= false;    
            for( j=0;  j < n -1;  j++ )
            {
                if (x[j] > x[j+1]){
                   temp = x[j];      
                   x[j] = x[j+1];
                   x[j+1] = temp;
                   flag = true;             
                  }
                 
                }
            }
  }
  
  void sSort()
  {
        for (int i = 0; i < n-1; i++)
        {
            int minIndex = i;
            for (int j = i+1; j < n; j++)
                if (x[j] < x[minIndex])
                    minIndex = j;
            int temp = x[minIndex];
            x[minIndex] = x[i];
            x[i] = temp;
        }
  }
  
  void accept()
  {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter size of the array");
      n = sc.nextInt();
      x=new int[n];
      for(int i=0; i<n; i++)
      {
        System.out.println("Enter array element "+(i+1));
        x[i] = sc.nextInt();
      }  

  }
  void display()
  {
      for(int i=0; i<n;i++)
        System.out.print(" "+x[i]);
  }
     MergeSort merge(MergeSort B)
  {
      MergeSort C= new MergeSort(n+B.n);
      int i = 0, j = 0, k = 0;
      while (i < n && j < B.n){
         if(x[i] < B.x[j])
            C.x[k++] = x[i++];
         else
            C.x[k++] = B.x[j++];
      }
      while(i < n)
         C.x[k++] = x[i++];
      while(j < B.n)
         C.x[k++] = B.x[j++];
      return C;
  }
  
  public static void main()
  {
      MergeSort A = new MergeSort();
      MergeSort B = new MergeSort();
      MergeSort C = new MergeSort();
      A.accept();
      B.accept();
      System.out.println("\nArray 1");
      A.display();
      System.out.println("\nArray 2");
      B.display();
      A.bSort();
      B.sSort();      
      System.out.println("\nSorted Array 1");
      A.display();
      System.out.println("\nSorted Array 2");
      B.display();
      C=A.merge(B);
      System.out.println("\nMerged Array");
      C.display();
    }  
}
This entry was posted in Array. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *