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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started