繁体   English   中英

此代码段的时间复杂度是O(n ^ 2)还是O(n ^ 3)

[英]Is the time complexity for this code segment O(n^2) or O(n^3)

我正在尝试计算以下两个函数的时间复杂度,但我感到困惑,因为在一个循环中我正在调用一个函数。 我们在计算时间复杂度时会考虑它吗? 该函数在if语句条件检查中调用,并且具有ao(n)。 另外,我正在使用Java中的内置排序功能对列表进行排序,我是否也必须对其进行计算?

public static List<Edge> getMSTUsingKruskalAlgorithm(int[][] graph, int[] singlePort) {

        List<Edge> edges = getEdges(graph);
        List<Edge> edges2 = getEdges(graph);
        DisjointSet disjointSet = new DisjointSet(graph.length);
        int chp=1000,x=-1,y=-1;
        List<Edge> mstEdges = new ArrayList<>();

        for(int i=0;i<singlePort.length;i++){
            chp=1000;
            x=-1;
            y=-1;
             for(Edge edge:edges){
                 if(( edge.x==singlePort[i]) && (!find(singlePort,edge.y))) {
                     if(edge.w<chp){
                         chp=edge.w;
                     x=edge.x;
                     y=edge.y;

                     }

                 }

             }

             int xSet = disjointSet.find(x);
             int ySet = disjointSet.find(y);

            if (xSet != ySet) {

                disjointSet.union(x,y);
                mstEdges.add(new Edge(x,y,chp));
                edges2.remove(new Edge(x,y,chp));
                for(Edge edge2:edges)
                {
                    if(edge2.x==x || edge2.y==x)
                        edges2.remove(edge2);
                }// end of loop

            }// end of if statement 

        }// end of loop 
        Collections.sort(edges2);

        for (Edge edge : edges2) {

            int xSet = disjointSet.find(edge.x);
            int ySet = disjointSet.find(edge.y);

            if (xSet != ySet) {

                disjointSet.union(edge.x, edge.y);
                mstEdges.add(edge);
            }
        }



         return mstEdges;


    }   



private static boolean find( int [] arr, int val)
    {
        boolean x= false;
        for (int i=0;i<arr.length;i++)
            if(arr[i]==val)
            { x=true;
             break;}

        return x;
    }

您的外部循环是O(n) ,其中n是singlePort中的元素数

您的内部循环是O(m) ,其中m是边列表中的边数。 在此循环中,您调用find(singlePort)函数-将其视为嵌套循环

find()函数为O(n) ,其中narr中为singlePort的元素数。

您具有三个嵌套循环级别,因此您会增加它们的时间复杂度。 注意:退出条件始终是运行时的良好指示

n * m * n = n^2 * m

如果m == n则您的算法为O(n * n * n) = O(n^3)

否则,从编写方式上,我们可以说的最好是:

O(n^2 * m)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM