I am new to coding and I was trying to create merge sort algorithm in java. I am getting too many errors and I am not able to figure out the exact mistake in the code. I feel my logic is correct but don't know which step(s) is causing the error. Could someone help me rectify the mistakes in the following code. Thank you
package com.company;
public class MergeSort_Array {
//Method created to print Input Array
public static void printInputArray(int inputArray[]) {
for (int i:inputArray) { //for-each loop
System.out.print(i + " ");
}
System.out.println();
}
//Function created to sort and merge Input Array:
public static void SortArray(int[] A) {
int midpoint = A.length / 2;
int[] left = new int[midpoint];
int[] right;
if (A.length % 2 == 0) {
right = new int[midpoint];
} else {
right = new int[midpoint + 1];
}
//Copying values from super Array to left Array:
for (int i = 0; i < midpoint; i++) {
left[i] = A[i];
}
//Copying elements from super Array to right Array:
for (int j = 0; j < right.length; j++) {
right[j] = A[midpoint + j];
}
//using Recursion
SortArray(left);
SortArray(right);
MergeArray(A, left, right);
}
// Creating a Function to merge left and right arrays.
public static void MergeArray(int[] result, int[] L, int[] R) {
//result array length = length of left array+ right array length
result = new int[L.length + R.length];
int i = 0, j = 0, k = 0;
while (k < result.length) {
if (L[i] < R[j]) {
result[k] = L[i];
i++;
} else
if (R[j] < L[i]) {
result[k] = R[j];
j++;
} else
if (i > L.length) {
while (j <= R.length) {
result[k] = R[j];
j++;
}
} else
if (j > R.length && i <= L.length) {
while (i <= L.length) {
result[k] = L[i];
i++;
}
}
k++;
}
}
public static void main(String[] args) {
int[] inputArray = { 2, 5, 4, 1, 7, 9, 6 };
MergeSort_Array ms = new MergeSort_Array();
ms.printInputArray(inputArray);
SortArray(inputArray);
for (int i: inputArray) {
System.out.println(i + " ");
}
}
}
resultwith a newint[]when you should really just write the result to the array passed in (i.e. get rid of the lineresult = new int[L.length + R.length];).