注册 登录
编程论坛 JAVA论坛

请问这个代码要怎么运行

温酒斩化腾 发布于 2018-02-01 20:33, 2162 次点击
public class QuickBest {

    // postcondition: a[lo..hi] is best-case input for quicksorting that subarray
    private static void best(int[] a, int lo, int hi) {

        // precondition:  a[lo..hi] contains keys lo to hi, in order
        for (int i = lo; i <= hi; i++)
            assert a[i] == i;

        if (hi <= lo) return;
        int mid = lo + (hi - lo) / 2;
        best(a, lo, mid-1);
        best(a, mid+1, hi);
        exch(a, lo, mid);
    }

    public static int[] best(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = i;
        best(a, 0, n-1);
        return a;
    }

    // exchange a[i] and a[j]
    private static void exch(int[] a, int i, int j) {
        int swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }


    public static void main(String[] args) {
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
       int n = Integer.parseInt(args[0]);  还有这行代码是什么意思?
        int[] a = best(n);
        for (int i = 0; i < n; i++)
            // StdOut.println(a[i]);
            System.out.print(alphabet.charAt(a[i]));
        System.out.println();
    }
}
4 回复
#2
林月儿2018-02-01 22:35
自动拆箱
#3
温酒斩化腾2018-02-01 22:51
回复 2楼 林月儿
不行啊,args数组是空的
#4
林月儿2018-02-03 19:47
那就加参数执行啊 命令行试试
#5
疯狂的小a2018-02-06 09:52
package com.demo;

/*
 * q1:
 * 这段代码,需要在eclipse中运行
 */
//请问这个代码要怎么运行
public class QuickBest {
    // postcondition: a[lo..hi] is best-case input for quicksorting that subarray
    private static void best(int[] a, int lo, int hi) {
        // precondition:  a[lo..hi] contains keys lo to hi, in order
        for (int i = lo; i <= hi; i++)
            assert a[i] == i;

        if (hi <= lo) return;
        int mid = lo + (hi - lo) / 2;
        best(a, lo, mid-1);
        best(a, mid+1, hi);
        exch(a, lo, mid);
    }

    public static int[] best(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = i;
        best(a, 0, n-1);
        return a;
    }

    // exchange a[i] and a[j]
    private static void exch(int[] a, int i, int j) {
        int swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    public static void main(String[] args) {
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        //因为args没有赋值,报数组指针越界异常了
        //int n = Integer.parseInt(args[0]);  //还有这行代码是什么意思?
        
        /*
         * q2:
         * 分析:
         * 1.这段代码的意思明显,就是给alphabet这个字符串排序
         * 2.n的取值应该是alphabet的长度,因此修改为下面这句话
         * 3.结果是ZBADECIHGKJLFSONQRPVUTXWYMmbadecihgkjlftonrqspwvuyxz
         */
        int n = alphabet.length();
        int[] a = best(n);
        for (int i = 0; i < n; i++)
            // StdOut.println(a[i]);
            System.out.print(alphabet.charAt(a[i]));
        System.out.println();
    }
}
1