Reputation: 273
In a directed graph I want an O(n+m) algorithm to sort lists in an adjacency list, so that names of vertices are sorted in increasing order in each list. The only one I can think of is to perform an insertion sort, on each of the list, but this definitely does not run in O(n+m). Can someone help me with this? Thanks
Upvotes: 0
Views: 4052
Reputation: 46
This solution does not utilize radix sort, but rather relies on order of the vertices in the adjacency list itself and the concept of incoming/outcoming edges.
This is assuming we have the graph G in the form of an adjacency list with the vertices already ordered. In particular, the data structure used for the adjacency list has to be an array (or any data structure that allows random access) of linked-lists. Each index of the array corresponds to a vertex in the graph, and the linked-list contains its adjacent vertices. Let n and m be the number of vertices and edges respectively. To illustrate, let's say we have the following directed graph G:
G:
[1] -> 4,5,2
[2] -> 3,1
[3] -> x (no neighbors)
[4] -> 1,2
[5] -> 4
G':
[1] ->
[2] ->
[3] ->
[4] ->
[5] ->
G':
[1] ->
[2] -> 1
[3] ->
[4] -> 1
[5] -> 1
Repeat this for all vertices in G. This process will take O(n+m) time.
G':
[1] -> 2,4
[2] -> 1,4
[3] -> 2
[4] -> 1,5
[5] -> 1
G-sorted:
[1] -> 2,4,5
[2] -> 1,3
[3] -> x
[4] -> 1,2
[5] -> 4
Similarly to step 2, this process will take O(n+m) time.
The undirected version is easier than this one, as you only have to perform step 2 once and not have to do it again in step 4 (no distinction between incoming-edges and out-coming edges)
Upvotes: 2
Reputation: 166
I don't have enough points ask this via comment yet, so I'm going to assume n is the number of vertices and m is the number of edges. By sorting by names of vertices, I'm going to assume you mean you want to sort alphabetically. If that's the case, then you might be able to use linear time sorting algorithms to achieve O(n+m), namely Radix sort. As long as the length of the vertex names is not huge, using Radix sort for each of the lists will take O(n+m) time total. Check out the wiki for radix sort:
https://en.wikipedia.org/wiki/Radix_sort
Upvotes: 0
Reputation: 15310
I don't believe this is possible. Your request for O(n+m) time suggests that you are looking for a topological sort of the graph. But while that will order the graph, it doesn't allow for the comparisons necessary to order the nodes/edges by another metric (the string node name).
Perhaps you have not stated the problem precisely?
Upvotes: 0