TADM2E 4.34

From Algorithm Wiki
Revision as of 00:13, 23 September 2016 by Rainhaven (talk | contribs) (Created page with "Assume array indices are zero based, use modified binary search to find the smallest integer missing: <pre> FindMinIntMissing(A): // elements in the array are continuous,...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Assume array indices are zero based, use modified binary search to find the smallest integer missing:

FindMinIntMissing(A):
    // elements in the array are continuous, the smallest missing integer is either 1 if A[0] is not 1, or n + 1 otherwise
    if(A[n - 1] - A[0] == n - 1)
    {
        if(A[0] > 1)
           return 1;
        else
           return n + 1;
    }
    // there is a gap in A, find the gap that is smallest
    else
    {
        return findGap(a, 0, n - 1);
    }

FindGap(A, first, last):
    // only two elements left, the smallest gap must be the integer right after A[first]
    if(last == first + 1)
        return A[first] + 1;
    // recursively looking for the partition containing the smallest gap
    else
       mid = (first + last) / 2;
       // first half doesn't have gap, looking for gap in the second half
       if(A[mid] - A[first] == mid - first)
           return findGap(a, mid, last);
       // looking for the gap in the first half
       else
           return findGap(a, first, mid);