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 smallest value in an array that is greater 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 smallest value in the array that is * strictly greater than the key. * @param stayInBounds If true, then {@code (a.length - 1)} will be returned in the case that the * key is greater than the largest value in the array. If false then {@code a.length} will be * returned. */ public static int binarySearchCeil(long[] a, long key, boolean inclusive, boolean stayInBounds) { int index = Arrays.binarySearch(a, key); index = index < 0 ? ~index : (inclusive ? index : (index + 1)); return stayInBounds ? Math.min(a.length - 1, index) : index; } /** * Returns the index of the smallest value in an list that is greater 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 smallest value in the list that is * strictly greater than the key. * @param stayInBounds If true, then {@code (list.size() - 1)} will be returned in the case that * the key is greater than the largest value in the list. If false then {@code list.size()} * will be returned. */ public static <T> int binarySearchCeil(List<? extends Comparable<? super T>> list, T key, boolean inclusive, boolean stayInBounds) { int index = Collections.binarySearch(list, key); index = index < 0 ? ~index : (inclusive ? index : (index + 1)); return stayInBounds ? Math.min(list.size() - 1, index) : index; } }