I finally got my program to sort my array but I cannot get it to add it. I am getting an error that reads:
MergeSorter.java:21: error: non-static method sumOfArray(int[],int) cannot be referenced from a static context
Code:
import java.util.Arrays;
public class MergeSorter{
public static void sort(int[] a)
{
if (a.length <= 1) { return; }
int[] first = new int[a.length / 2];
int[] second = new int[a.length - first.length];
for (int i = 0; i < first.length; i++)
{
first[i] = a[i];
}
for (int i = 0; i < second.length; i++)
{
second[i] = a[first.length + i];
}
sort(first);
sort(second);
merge(first, second, a);
int sum =sumOfArray(a, a.length-1);
}
private static void merge(int[] first, int[] second, int[] a){
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length){
if (first[iFirst] < second[iSecond]) {
a[j] = first[iFirst];
iFirst++;
}
else{
a[j] = second[iSecond];
iSecond++;
}
j++;
}
while (iFirst < first.length){
a[j] = first[iFirst];
iFirst++; j++;
}
while (iSecond < second.length){
a[j] = second[iSecond];
iSecond++; j++;
}
}
public int sumOfArray(int[] a, int n){
if (n == 0)
return a[n];
else
return a[n] + sumOfArray(a, n-1);
}
}