Sort both lists first with quicksort: O (n * log (n). Then compare the lists by looking at the lowest values ββand add common values. For example, in lua):
function findIntersection(l1, l2) i, j = 1,1 intersect = {} while i < #l1 and j < #l2 do if l1[i] == l2[i] then i, j = i + 1, j + 1 table.insert(intersect, l1[i]) else if l1[i] > l2[j] then l1, l2 = l2, l1 i, j = j, i else i = i + 1 end end return intersect end
which is O(max(n, m)) , where n and m are the sizes of the lists.
EDIT: quicksort is recursive, as said in the comments, but it seems like a non-recursive implementation
Wookai Jan 30 '09 at 21:47 2009-01-30 21:47
source share