Page 588 - ComputerScience_Class_11
P. 588
Program 13 Define a class merge sort to accept two arrays and print their sum and then sort them using
merge sort. The data members and member method are defined as follows:
Data Members
Size : store the size of the array
Member Methods
void merge(int[], int, int, int) : to merge two arrays
void sort(int[], int, int) : to sort an array using merge sort
int[] add(int[], int[], int) : to input two arrays and find the sum
void printArray(int[]) : to print the array
Write the main program by specifying the class and defining the methods as given.
1 import java.util.*;
2 class mergesort
3 {
4 void merge(int arr[], int l, int m, int r)
5 {
6 //using mergesort technieque to sort the array
7 //sizes of the 2 subarrays
8 int n1 = m - l + 1;
9 int n2 = r - m;
10 int L[] = new int [n1];
11 int R[] = new int [n2];
12 //dividing and copying the data into temp arrays
13 for (int i=0; i<n1; ++i)
14 {
15 L[i] = arr[l + i];
16 }
17 for (int j=0; j<n2; ++j)
18 {
19 R[j] = arr[m + 1+ j];
20 }
21 // Initial indexes of first and second subarrays
22 int i = 0, j = 0;
23 // Initial index of merged subarry array
24 int k = l;
586 Touchpad Computer Science (Ver. 3.0)-XI

