Java递归和合并排序 [英] Java recursion and Merge Sort

查看:73
本文介绍了Java递归和合并排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Java编写一个简单的合并排序程序,在Eclipse中看到很多红色.我仍然是初学者,还不太清楚怎么了.谢谢.

I'm trying to write a simple merge sort program in Java, I'm seeing a lot of red in Eclipse. I'm still a beginner, and don't quite see whats wrong. thanks.

-凯尔

public class merge{ 
public static int[] mergeSub(int[] array, int left, int right){
        if(left<right)
        {
        int mid = (left+right)/2;
        int[] a = mergeSub(array, left, mid);
        int [] b = mergeSub(array, mid+1, right);
        return merge(a, b);

}
        int[] arr=new int[1];
        arr[0]=arr[left];
        return arr;
}

static int[] merge(int[] left, int[] right){
        int index =0; int indexLeft =0; int indexRight=0;
        int[] result = new int[left.length+right.length];

        while(indexLeft<left.length && indexRight<right.length){
                if(left[indexLeft] <= right[indexRight])
                {
                        result[index]=left[indexLeft];
                        index++;
                        indexLeft++;

                }
                else{
                        result[index]=right[indexRight];
                        index++;
                        indexRight++;
                }
        }

        if (indexLeft<left.length){
                while(indexLeft<left.length){
                        result[index]=left[indexLeft];
                        indexLeft++; index++;
                }
        }
        if (indexRight<right.length){
                while(indexRight<left[indexRight]){
                        result[index]=right[indexRight];
                        indexRight++; right[indexRight]++;
                }
        }
        return result;
}



public static void main(String args[]){

        int[] array = {2, 4, 5, 7, 5, 6, 3, 5, 7, 8};
        System.out.println(mergeSub(array, 0, 9));
}}

推荐答案

您应该首先在Eclipse中减少它的红色:-)

You should start by making it less red in Eclipse :-)

当您将鼠标悬停在错误上时,它会告诉您错误是什么.例如,在您的mergeSub代码中,您已经将leftright声明为本地数组,即使leftright已经被声明为int参数.用不同的名称命名您的局部变量.

When you mouse over the error, it tells you what the error is. For example, in your mergeSub code you're declaring left and right as local arrays even though left and right are already declared as int parameters. Name your local variables differently.

冲洗并重复.

这篇关于Java递归和合并排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆