Friday, 15 July 2011

algorithm - Finding elements that are present in one set not the other -


I have two sets A and B

  A - 1 2 6B - - 1 2 3 4  

When I set A with B, I need to get value 6 as the output and 4 value as the output when set B A Is compared to.

I wonder what would be the best algorithm to do this? I have written one, but it has got quadratic complexity, it basically repeats a set and inside the loop, the second set repeats the value to check the existence. I am considered ineligible as such.

Context

I have a set of values ​​in the database, which I am the UI. Users can remove or add new items to the list and press the "Save Changes" button, which will continue to make all the changes in the database. So here I insert new added items into the database and delete deleted items.

So I pass the set in which the items have been added and already existed. I load another set that contains all the items from the database. Now if I apply the above algorithm to set A (new list) with set A (database list) and take the items in the set and not in the set, I get all newly added items I will compare it with Seta, and all the items present in the set and not in the set are deleted. I am open to suggestions for better algorithms.

Any help would be great.

If both sets are sorted then both sets can start from the beginning and through them Let's compare, compare the first elements to see which other sets are missing. It works in linear time.

For the ordered sets, first order them in the O (n log (n)) and then by comparing them in linear time, o (n log (n)). Based on the details of your application, it is possible to keep this set sorted all the time, which makes it easier to compare them when needed.


No comments:

Post a Comment