Implement a method that meets the following requirements using JAVA:
(a) Calls mergesort to sort an array/list of at least 5 integers (b) Prints the list before and after sorting.
Source Code in Java:
class MergeSort
{
void merge(int arr[],int left,int mid,int right) //method to merge
two subarrays
{
//creating temporary arrays for the two subarrays
int n1=mid-left+1;
int n2=right-mid;
int L[]=new int[n1];
int R[]=new int[n2];
for (int i=0;i<n1;i++)
L[i]=arr[left+i];
for (int j=0; j<n2;j++)
R[j]=arr[mid+1+j];
int i=0,j=0;
int k=left;
//merging the two subarrays into original array
while(i<n1 && j<n2)
{
if (L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[j];
j++;
k++;
}
}
void mergeSort(int arr[],int left,int right) //method to implement
merge sort
{
if (left<right)
{
int mid=(left+right)/2;
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
merge(arr,left,mid,right);
}
}
void mergeFunc(int arr[]) //method to call a merge sort for an
array and print the array before and after sorting
{
//printing array
System.out.print("The array before sorting: ");
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
mergeSort(arr,0,arr.length-1); //calling merge sort
//printing array
System.out.print("The array after sorting: ");
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
//testing the function
int arr[]={4,2,5,8,3,10,6,1,9,7};
MergeSort ob=new MergeSort();
ob.mergeFunc(arr);
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.