In: Computer Science
JAVA please write this method
public static void recursiveMergeSort(int[] arr) {
}
class MergeSort {
public static void merge(int[] result, int[] first, int[] second)
{
int i, j, k;
i = j = k = 0;
//while till both completly copied
while ( i < first.length || j < second.length )
{
if ( i < first.length && j < second.length )
{
//compate element
if ( first[i] < second[j] )
result[k++] = first[i++];
else
result[k++] = second[j++];
}
else if ( i == first.length )
result[k++] = second[j++]; //while first completed then 2nd copy
else if ( j == second.length )
result[k++] = first[i++]; //while second completed then 1st copy
}
}
public static void recursiveMergeSort(int[] arr)
{
int[] Arrayleft, Arrayright;
// if array consist 1 element
if ( arr.length == 1 )
{
return;
}
int midindex = arr.length/2;//get mid index
Arrayleft = new int[midindex]; //array to hold left part
for ( int i = 0; i < midindex; i++ )
Arrayleft[i] = arr[i];//copy elements
Arrayright = new int[arr.length-midindex]; //array to hold right part
for ( int i = 0; i < arr.length-midindex; i++ )
Arrayright[i] = arr[i+midindex];//copy elements
recursiveMergeSort( Arrayleft ); //call recusively
recursiveMergeSort( Arrayright ); //call recusively
merge( arr, Arrayleft, Arrayright ); //Merge left and right array
}
static void DisplayArray(int array[])
{
int size = array.length;
for (int i = 0; i < size; ++i)
System.out.print(array[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int array[] = { 4,8,52,41,14,96,7 };
System.out.println("Original Array");
DisplayArray(array);
recursiveMergeSort(array);
System.out.println("Sorted Array");
DisplayArray(array);
}
}
/*
Output
Original Array
4 8 52 41 14 96 7
Sorted Array
4 7 8 14 41 52 96
*/