Like graph in form of a list :
1 : 2 -> 3
2 : 3 -> 4 -> 1
3 : 2 -> 1 -> 4
4 : 3 -> 2
whew 1 : 2 -> 3 means that node 1 is connected to nodes 2 and 3.
So the output should be each node list sorted :
1 : 2 -> 3
2 : 1 -> 3 -> 4
3 : 1 -> 2 -> 4
4 : 2 -> 3
So, this can be done in n * O(log n) time by sorting each list, but what is the most optimal algorithm for this problem ?
Sorting all separate lists would be easiest way to get what you want. However, if you have n nodes, you have to sort n lists. Each list could have n-1 entries. Sorting 1 list of n-1 entries would have complexity O(n*log(n)). Your total complexity would be O(n²*log(n)).
You could try to go under that by sorting your lists sequentially and exploiting that information. From your example i assume that your graph is undirected, which allows for the following optimization.
An example first:
Then your first list would be done. You could then add ‘1’ to the
lists of node 2 and 3 (as 1 will appear in their lists as first
item). This would give you the start of those lists. Then you move
on to the list of node 2.
(1), you could skip all that node during sorting. You could do a
quick pass through your linked list and remove 1 from the set. Then
you sort the rest (which would give 3->4) and append it to the 1 you
already had. As with 1, you now have the full sorted list of 2 and
you can add ‘2’ to the list of 3 and 4.
rest. This would give you 4 and you append that to what you already have to get 1->2->4. Add 3 to the list of node 4.
More formally:
This should be faster than sequentially sorting all the lists as the lists to be sorted are smaller.