What is the best data-structure for doing following operation quickly
- Insert
- Find.
Thanks
Avinash
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A good implementation for graph adjancency lists is using dynamically allocated vectors of integers.
Let’s suppose you have at most N nodes in your graph. You can store the graph in an array of N dynamically allocated vectors of integers.
It will look like this:
vector[N]
To insert a edge from node x to node y you use:
vector[x].push(y)
This way if the graph is sparse ( doesn’t have a lot of edges) you can find all the outgoing edges of a node quickly.
If you want to find if there’s an edge between x and y you have to go through vector[x] and search for it. If you want to speed that up you can additionaly use a 2 dimensional boolean array if the number of nodes is small ( less then 1000 is reasonable).
If you have a lot of nodes and want to speed that operation up you can use a hashmap.