首页 > 解决方案 > 任务是在 O(n log n) 中创建一个代码,我写的这段代码的时间复杂度是多少?

问题描述

我正在学习大 O 和时间复杂度,我发现很难理解。你能帮我理解我写的这段代码的时间复杂度吗?

基本上,任务是遍历一个数字数组并计算满足的对数arr[i] > arr[j]。就像这段代码中给出的数组一样,arr = {7, 3, 8, 1, 5}找到的对应该是(7, 3),(7, 1),(7, 5),(3, 1),(8, 1),(8, 5),对的总数是6

任务是创建时间复杂度为 O(n log n) 的代码,但大 O 仍然让我感到困惑。我不确定这是否是 O(n^2) 并且不确定程序是否会因更大的数组而变慢。

public class Test {
    public static void main(String[] args) {
        int[] arr = {7, 3, 8, 1, 5};
        System.out.println();
        System.out.println("The number of pairs is " + countPair(arr));
    }
    public static int countPair(int[] arr) {
        int i = 0, j = 1;
        int ctr = 0;
        int len = arr.length;
        while (i < len) {
            if (j == len) {
                i++;
                j = 1;
            }
            else if (i < j && (arr[i] > arr[j])) {
                ctr++; // Counting pairs
            }
            j++;
        }
        return ctr;
    }
}

输出:

The number of pairs is 6

标签: javaarraystime-complexitybig-o

解决方案


推荐阅读