且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我为这个程序是O(n)运行时而疯狂吗?我的助教说是O(n ^ 2)

更新时间:2023-02-13 21:57:20

作为其他问题是该问题的重复部分,让我在此处发布答案.

As the other question was a duplicate of this one, let me post my answer here.

当您增加i或减少end时,代码为O(n).无论如何,您将其余工作(n)减少了一个.

The code is O(n) as you either increase i or reduce end. In any case, you decrease the rest of work (n) by one.

对于即将到来的作业:您可以通过尝试轻松地测试关于big-O的想法.大多数时候,测试的数量不需要很大.这不是证明,但可以为您提供一个很好的提示,无论您的想法正确与否.

For your upcoming homework: You can test your thoughts about big-O easily just by trying out. Most of the time the number of tests doesn't need to be very big. It will not be a proof but it gives you a good hint if your thoughts are correct or not.

这是我针对100个测试所遇到问题的代码.它产生100对数字:数组的长度和循环数.您将这个列表带到图表中.

Here's is my code for your problem with 100 tests. It produces 100 pairs of numbers: The length of the array and the number of loops. You take this list and bring it to a graph.

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        Random random = new Random();

        for (int i = 0; i < 100; i++) {
            int[] array = new int[random.nextInt(10000 - 10) + 10]; // between 10 and 9999 numbers long
            for (int j = 0; j < array.length; j++) array[j] = random.nextInt();

            main.organize(array);
        }
    }

    private int[] organize(int[] array) {
        long loops = 0;
        int end = array.length-1;

        // I've shorten your code here. This does the same with less breaks
        for (int i = 0; i < end; i++) {
            while(i < end && array[i] % 2 == 0) {
                swap(array, i, end--);
                loops++;
            }
        }

        System.out.printf("%d\t%d\n", array.length, loops);
        return array;
    }

    private void swap(int[] array, int a, int b) {
        int t = array[a];
        array[a] = array[b];
        array[b] = t;
    }
}

图形看起来像一条直线.因此,您的证明应为O(n),对吧?

And the graph looks like a straight line. So your proof should result in O(n), right?