【问题标题】:I'm in the process of writing a Merge Sort program, I'm getting the following errors:我正在编写合并排序程序,我收到以下错误:
【发布时间】:2013-03-31 12:42:07
【问题描述】:

请考虑以下代码:

public class MergeSort {




public static void main(String[] args) {

            int[] A = new int[10];

                // Printing the Initial Arrays
                     System.out.println("Array Elements before Sorting are as follows:");

                       for(int i = 0;i < A.length;i++){

                        System.out.println(A[i] + " ");
                                                      }

                        // Call the MergeSort Method here


                        // Printing Sorted Array here

                    System.out.println("Sorted Array are as follows:");

                    //for(int j = 0;j < result.length;i++){

                    //System.out.println(result[i] + " ");
                    //}


    public static int[] merge_sort(int[] B){

        if(B.length <=1){

            return B;

        }

        int midpoint = B.length/2;

        int[] left = new int[midpoint];

        int[] right;

        if(B.length % 2 == 0){

            right = new int[midpoint];

        }else {
            right = new int[midpoint+1];

              }

        // An Extra Array to store the result

        int[] result = new int[B.length];

        // Populating the array in the left array

        for (int i = 0; i < midpoint; i++){

            left[i] = B[i];

        }

        // Populating in the right array
        int x = 0;
        for (int j=midpoint;j<B.length;j++){

            right[x] = B[j];
            x++;
        }

        // Using recursion to divide the array in left and right again and again

        left = merge_sort(left);
        right = merge_sort(right);


    }// END OF METHOD merge_sort




}// END MAIN METHOD




}// END OF CLASS MergeSort

我在 Eclipse 中的以下行中收到以下错误:十字符号表示 Eclipse 中的错误点:

X public static int[] merge_sort(int[] B){

错误说:参数merge_sort的非法修饰符;只允许决赛。

X 返回 B;

错误说:void 方法不能返回值。我已经将方法返回类型定义为 整数数组为什么会出现这个错误?

X left = merge_sort(left); X right = merge_sort(right);

错误提示:方法合并排序未定义为 MergeSort 类型

【问题讨论】:

  • 如果你有一个好的缩进代码,一半的问题就解决了!
  • 有什么好的教程可以学习缩进吗?

标签: java algorithm sorting merge


【解决方案1】:

你不能在另一个方法中拥有一个方法!

您的 merge_sort() 方法在 main 方法中!

【讨论】:

  • 哦,我的错。愚蠢的错误。
【解决方案2】:

我认为,如果您修复代码中的缩进,问题就会很明显。您的 merge_sort 方法在您的 main 方法中声明。

只需将 }// END MAIN METHOD 右大括号移到上面声明 merge_sort 的行上,它应该可以编译。

【讨论】:

  • 没问题 - 如果我们帮助解决了您的问题,请考虑接受答案
猜你喜欢
  • 2017-07-18
  • 2020-11-09
  • 2013-05-03
  • 2017-02-22
  • 2021-02-27
  • 1970-01-01
  • 2018-11-24
  • 2019-11-22
  • 2011-01-11
相关资源
最近更新 更多