views:

72

answers:

2

hi... am looking for an efficient algorithm to synchronize two arrays..

Lets say a1 and a2 are two arrays given as input...

a1 - C , C++ , Java , C# , Perl

a2 - C++ , Python , Java , Cw , Haskel

output 2 arrays:

Output A1 : C , C++ , Java

Output A2 : Cw , Haskell , Python

Output A1 : 1) items common to both arrays 2) items only in a1 and not in a2

Output A2:

items only in a2

thanks in advance... raj...

+4  A: 
  1. Sort both arrays with an efficient sorting algorithm, complexity of O(n.log(n))
  2. Build the output arrays initially empty
  3. Compare the first element a1 of sorted A1 to the first element a2 of sorted A2
    • Equal means is in both arrays, put a1 into OutputA1
    • a1 < a2 means a1 is only in A1, a1 now necomes next element in sorted A1, put a1 into OutputA1
    • else a2 < a1 means a2 is only in A2, a2 now necomes next element in sorted A2, put a2 into OutputA2

Do this until you processed all elements in the sorted arrays, complexity of O(n).

jdehaan
thanks a lot jdehaan for replying.. :) is there a way to do this without sorting, because for 50K entries sorting might be a overhead..
Raj
sorting is O(n.log(n)), 50K is pretty manageable in arrays, do not worry. There is an intrinsic complexity in the problem you are trying to solve. If you don't have it with sorting, you'll transfer it to the part that has to check the elements. There is no magic solution.
jdehaan
thanks, jdehaan...
Raj
I think the only potential way to do this faster than O(n*log(n)) would be to use a hash table. Then you could get O(n) time, *if* you had a good hashing function.
ESRogs
But how would you figure out that an item is in A2 but not in A1 without some poor algorithm like linear search (for each item, what means O(n^2))?
jdehaan
A: 

Knuth probably said something on this problem - http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming The books are expensive, but if you have access to them, you'll probably find some wisdom in there.

bert hubert
And you think that he should bought this stack of books who almost nobody reads, (and I am sure that you did not either) since I did not noticed MIX word in his post.
ralu
No, I did not suggest that. Also, if you follow the link and look at the table of contents, you'll note that loads of material has nothing to do with MIX. Oh well.
bert hubert