I'm trying to calculate the time complexity for the following two functions but I'm confused because inside one of the loops I'm calling a function. Do we consider it when calculating the time complexity. The function is called in the if statement condition check and it have ao(n). Also, I'm Sorting a list using a build in sorting function in java, Do I have to calculate it too?
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;
}
Your outer loop is O(n)
where n
is the number of elements in singlePort
Your inner loop is O(m)
where m
is the number of edges in the edges list. Within this loop you call the find(singlePort)
function - treat it like a nested loop
the find()
function is O(n)
where n
is the number of elements in the arr
which is singlePort
.
You have three levels of nested loops, thus you multiply their time complexities. NOTE: the exit condition is always a good indicator of the runtime
n * m * n = n^2 * m
If m == n
then your algorithm is O(n * n * n) = O(n^3)
Otherwise, from the way it is written, the best we could say is:
O(n^2 * m)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.