Here you can find the source of findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min, final int[] max)
public static void findMaxOverlap(final int[] overlapRange, final int[] outputRange, final int[] min, final int[] max)
//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; } }