Question: The attached java file contains the source for the MergeSort, there is something you need to figure out to make the porgram work corretly. Please

The attached java file contains the source for the MergeSort, there is something you need to figure out to make the porgram work corretly. Please again NEVER DELETE ANYTHING, you ONLY need to add 2 words to the method "merge" and that's is, the sorting algorithm will function as expected.

import java.util.Arrays;

public class MergeSort{

private static int[] a;

private static void divide(int[] a){

if(a.length <=1) return;

int[] firstHalf = new int[a.length/2];

int[] secondHalf = new int[a.length - firstHalf.length];

for(int i = 0; i < firstHalf.length; i++) firstHalf[i] = a[i];

for(int i = 0; i < secondHalf.length; i++) secondHalf[i] = a[firstHalf.length+i];

divide(firstHalf);

divide(secondHalf);

merge(firstHalf, secondHalf);

}

private static void merge(int[] firstHalf, int[] secondHalf){

int firstHalfIndex = 0;

int secondHalfIndex = 0;

int aIndex = 0;

for(;firstHalfIndex < firstHalf.length && secondHalfIndex < secondHalf.length;){

if(firstHalf[firstHalfIndex] < secondHalf[secondHalfIndex]){

a[aIndex] = firstHalf[firstHalfIndex];

firstHalfIndex++;

}else{

a[aIndex] = secondHalf[secondHalfIndex];

secondHalfIndex++;

}

aIndex++;

}

for(;firstHalfIndex < firstHalf.length;firstHalfIndex++, aIndex++){

a[aIndex] = firstHalf[firstHalfIndex];

}

for(; secondHalfIndex < secondHalf.length; secondHalfIndex++, aIndex++){

a[aIndex] = secondHalf[secondHalfIndex];

}

}

public static void main(String[] args){

int[] array = {10, 8, 4, -6, 2, 1, 0, -9, 3};

a = array;

divide(a);

System.out.println(Arrays.toString(a));

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!