java - 程序不返回

标签 java recursion divide-and-conquer

我想在数组中找到一个“峰值”(a1 ai+1>...>an 的值,ai 是此处的峰值)。我在这里使用分而治之的方法来获得更佳的解决方案。对于“6 1 3 50 70 100 48”,它将打印“70 100 48 4”,这很好(70 < 100 和 100 > 48),但它不返回 Integer.toString(a[m]),它返回“阵列没有峰值”。我尝试删除字符串并使用 int,但我遇到了完全相同的问题。

public class Main {

    public int n, a[];

    void read() {
        File file = new File("src/com/fmi/Vector.txt");
        Scanner sc;

        try {
            sc = new Scanner(file);
            int i = 0;
            if (sc.hasNextInt()) {
                n = sc.nextInt();
            }
            a = new int[n];
            while (sc.hasNextInt()) {
                int aux = sc.nextInt();
                a[i] = aux;
                i++;
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        }
    }

    String search(int p, int u) {
        int m;
        System.out.println(p + " " + u);
        if (p == u) {
            return "0";
        } else {
            m = (p + u) / 2;
            System.out.println(a[m - 1] + " " + a[m] + " " + a[m + 1] + " " + m);
            if (a[m - 1] < a[m] && a[m] > a[m + 1]) {
                return Integer.toString(a[m]);
            } else if (a[m - 1] < a[m] && a[m] < a[m + 1]) {
                search(m, u);
            } else if (a[m - 1] > a[m] && a[m] > a[m + 1]) {
                search(p, m);
            }
        }
        return "Array has no peak!";
    }

    void display() {
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println(" ");
        for (int i = 0; i < n; i++) {
            System.out.print(i + " ");
        }
    }

    public static void main(String[] args) {
        Main obj = new Main();
        obj.read();
        System.out.println(obj.search(0, obj.n));
        obj.display();
    }
}

最佳答案

您正在调用搜索,但没有对结果执行任何操作。 你应该做类似的事情

return search(m,u);

关于java - 程序不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34593403/

相关文章:

arrays - 分而治之k-way-merge算法的时间和空间复杂度

algorithm - 我对最近对问题的分而治之算法的逻辑有什么问题?

c - 如何在 Linux 上从 Java 代码调用 C 函数

java - Android Studio - WebView 使用文件 :///to display local website 后服务崩溃

recursion - 在 Ocaml 中使用 "and"进行多个相互递归函数

c - 堆栈问题: Local variables vs Arithmetics

Java递归计数

algorithm - 证明合并排序输出输入的排列

java - 如何避免代码重复初始化最终属性?

java - 阶乘上限