Java Array Max Value findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min, final int[] max)

Here you can find the source of findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min, final int[] max)

Description

find Max Overlap

License

Open Source License

Declaration

public static void findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min,
            final int[] max) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

public class Main {
    public static void findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min,
            final int[] max) {
        final int minStart = findMinimaGreaterOrEqual(min, overlapRange[0]);
        final int correctedMinStart = backtrackForHalfInIntervals(minStart, max, overlapRange[0]);
        outputRange[0] = correctedMinStart;
        final int maxEnd = findMaximaLessOrEqual(min, overlapRange[1]);
        outputRange[1] = maxEnd;/*  ww w  .ja v  a2s . c  o m*/
    }

    private static int findMinimaGreaterOrEqual(final int[] min, final int elt) {
        int tempPos = Arrays.binarySearch(min, elt);
        if (tempPos >= 0) {
            tempPos = backTrack(min, tempPos);
        } else {
            tempPos = -(tempPos + 1);
            tempPos = Math.min(min.length - 1, tempPos);
        }
        return tempPos;
    }

    private static int backtrackForHalfInIntervals(final int minStart, final int[] max, final int overlapStart) {
        int minVal = minStart;
        for (int i = minStart - 1; i >= 0; --i) {
            if (max[i] >= overlapStart) {
                minVal = i;
            }
        }
        return minVal;
    }

    private static int findMaximaLessOrEqual(final int[] min, final int elt) {
        int tempPos = Arrays.binarySearch(min, elt);
        if (tempPos >= 0) {
            tempPos = forwardtrack(min, tempPos);
        } else {
            tempPos = -(tempPos + 1);
            if (tempPos > 0) {
                --tempPos;
            }
            tempPos = Math.min(min.length - 1, tempPos);
        }
        return tempPos;
    }

    public static int backTrack(final int[] arr, int pos) {
        while (pos > 0 && arr[pos - 1] == arr[pos]) {
            --pos;
        }
        return pos;
    }

    public static int forwardtrack(final int[] arr, int pos) {
        while (pos < arr.length - 1 && arr[pos + 1] == arr[pos]) {
            ++pos;
        }
        return pos;
    }
}

Related

  1. findMaxDiff(byte[] rand, byte[] newRand)
  2. findMaximumUnitFor(long elapsed, int specifiedMax)
  3. findMaxIndex(final int[] array)
  4. findMaxIndex(int[] a)
  5. findMaxIndex(int[] arr)
  6. findMaxValue(int[] array)
  7. findMaxValueIndex(double[] d)
  8. max(boolean useInt, int... value)
  9. max(byte[] arr)