合并排序数组然后添加

时间:2015-04-08 12:48:13

标签: sorting merge

我终于得到了我的程序来对我的数组进行排序,但我无法让它添加它。我收到的错误是:

MergeSorter.java:21: error: non-static method sumOfArray(int[],int) cannot be referenced from a static context

代码:

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);
   }
}

3 个答案:

答案 0 :(得分:0)

让它静止吗? 喜欢:

public static int sumOfArray(int[] a, int n)
{
    if (n == 0)
        return a[n];
    else
        return a[n] + sumOfArray(a, n-1);
}

答案 1 :(得分:0)

请参阅此帖子:Non-static variable cannot be referenced from a static context

简而言之,您需要将方法设为静态,或者在类的实例上调用它。

答案 2 :(得分:0)

一个简单的解决方法就是改变

 public int sumOfArray(int[] a, int n)

 public static int sumOfArray(int[] a, int n)

否则你必须创建一个MergeSorter对象并调用sumOfArray方法:

 int sum =new MergeSorter().sumOfArray(a, a.length-1)