0

Could someone provide a possible loop invariant for the following simple algorithm:

Input: A[0,...,n-1] and B[0,...,m-1], each might contain repeated elements

Output: the first pair of (i,j) such that A[i] == B[j].

Algorithm:

for i <- 0 to n-1
    for j <- 0 to m-1
        if A[i] = B[j] then
           return (i,j)
        endif
    endfor
endfor
return null

So far, I've got only one solution that might or might not work:

S = {(i,j) | A[0,...,i-1] and B[0,...,j-1] has no common elements}

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
  • Are the arrays sorted? – G. Bach Apr 02 '13 at 00:02
  • What is the "first pair of ..." - the one with the smallest `i`? The smallest `j`? The smallest `i+j`? There is more than one possible ordering of the pairs, so you'll have to specify what that means before you can get an answer... For example, if `A[0] == B[m-1]`, would that be "first" over `A[1] == B[1]`? – twalberg Oct 03 '13 at 19:04
  • @twalberg The loop invariant of the algorithm shown above. I think with the algorithm specified, the *first pair* should be clear :) – gongzhitaao Oct 03 '13 at 21:55

1 Answers1

2

At the beginning of the qth iteration of the second loop inside the pth iteration of the first loop, A[i] != B[j] for all i = 0...p - 1, j = 0...q - 1.

abeln
  • 3,749
  • 2
  • 22
  • 31
  • basically, your solution is identical to what i've included in my question. Actually this is the only one i've worked out. Theoretically, infinite numbers should be found... – gongzhitaao Apr 01 '13 at 23:32