[英]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)
,其中n
是arr
中為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.