I have 2 large arrays of objects, what is more efficient algorithm to know they contain the exact same members other than the nested loop comparison?
1) first thing, compare length, if not equal, gone! 2) Make copy of each, O(n) 3) Sort both copy, O(n * lg n) 4) Compare each pair O(n) Over all O(n * lg n)It is much better than nested loop, which is O(n*n). If the n = 13,000,000,000, use your calculator, you will see huge speed difference. Of course, if n = 130, the nested loop algorithm is simple and better. Since the time saving on computing does not worth the programming effort and the overhead of the complicated algorithms.How to compare two Objects? Define a java.util.Comparator for the object you want to compare, and then the algorithm would be the same.Since speed is the major concern, do not use Vector, use array instead, according to some research; Vector is at least 3 times slower than straight array.Here is an example of how to use Comparator: http://www.geocities.com/developergrp/Code/SortBy.
Related Questions
- I have 2 large arrays of objects, what is more efficient algorithm to know they contain the exact same members other than the nested loop comparison?
- I am interested in monogramming a mans tie. How large should I make the initials and is there an exact placement for them?
- Is it possible to buy bags of house coal which contain large chunks of coal?