Java tutorial
//package com.java2s; /* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Arrays; import java.util.Collections; import java.util.List; public class Main { /** * Returns the index of the largest value in an array that is less than (or optionally equal to) * a specified key. * <p> * The search is performed using a binary search algorithm, and so the array must be sorted. * * @param a The array to search. * @param key The key being searched for. * @param inclusive If the key is present in the array, whether to return the corresponding index. * If false then the returned index corresponds to the largest value in the array that is * strictly less than the key. * @param stayInBounds If true, then 0 will be returned in the case that the key is smaller than * the smallest value in the array. If false then -1 will be returned. */ public static int binarySearchFloor(long[] a, long key, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(a, key); index = index < 0 ? -(index + 2) : (inclusive ? index : (index - 1)); return stayInBounds ? Math.max(0, index) : index; } /** * Returns the index of the largest value in an list that is less than (or optionally equal to) * a specified key. * <p> * The search is performed using a binary search algorithm, and so the list must be sorted. * * @param list The list to search. * @param key The key being searched for. * @param inclusive If the key is present in the list, whether to return the corresponding index. * If false then the returned index corresponds to the largest value in the list that is * strictly less than the key. * @param stayInBounds If true, then 0 will be returned in the case that the key is smaller than * the smallest value in the list. If false then -1 will be returned. */ public static <T> int binarySearchFloor(List<? extends Comparable<? super T>> list, T key, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, key); index = index < 0 ? -(index + 2) : (inclusive ? index : (index - 1)); return stayInBounds ? Math.max(0, index) : index; } }