I am pulling my hair understanding the runtime for the naive (no heap) implementation of Dijsktra algorithm, and potentially if there is a better code for this naive implementation.
The runtime mentioned in theory for naive implementation is O(VE), where E is # of edges and V is the # of Vertices. Is this correct or did I misread? Is this following code running in O(VE) time? How? Is there a better way to implement this naively?
internal void DijkstraShortestPathCompute()
{
// initialize shortest paths for s being 0 and rest as indefinite
// loop until all vertices are explored: hashset condition
// loop all the vertices: 1 -> N
// find unexplored and vertex with smallest edge
// if no smallest edge disconnect and break
// Add to hashset
// relax its neighbors - update the length of each neighbor if they aren't seen and their current distance smaller than prev
// while all vertices are not explored
while(Computed.Count < MAX_VERTEX)
{
// find the smallest edge
(int w, int lvw) = (-1, MAX_VALUE);
for(int j = 1; j <= MAX_VERTEX; j++)
{
// only if its not computed before and its dijsktra score is the smalles
if(!Computed.Contains(j) && ShortestPath[j] < lvw)
{
lvw = ShortestPath[j];
w = j;
}
}
// disconnected graph - walk out
if(w == -1)
break;
// add it to the explored space
Computed.Add(w);
// forward relax the edges so that next iteration we can find the smallest potential edges
foreach((int n, int l) in AdjacencyList[w])
{
// if it is not visited and its calculated distance is smallest only then update
if(!Computed.Contains(n) && ShortestPath[w] + l < ShortestPath[n])
ShortestPath[n] = ShortestPath[w] + l;
}
}
}
I can see that we are running the outer following loop in O(V-1), where V is # of Vertices
while(Computed.Count < MAX_VERTEX)
The following first inner loop in O(V) times
for(int j = 1; j <= MAX_VERTEX; j++)
and this second inner loop in O(E) times, where E is # of edges
foreach((int n, int l) in AdjacencyList[w])
How come O(V-1 (V + E)) is equal to O(VE)?
Computed? What isShortestPath? Why are they not initialised by the function?