Java Binary Search binarySearch(long[] data, long key, int low, int high)

Here you can find the source of binarySearch(long[] data, long key, int low, int high)

Description

binary Search

License

Open Source License

Return

index \in [low,high] s.t. data[index] = key, or -1 if not found

Declaration

public static int binarySearch(long[] data, long key, int low, int high) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2002 - 2006 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   w w w. ja v  a 2 s .  co m*/
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * @return index \in [low,high] s.t. data[index] = key, or -1 if not found
     */
    public static int binarySearch(long[] data, long key, int low, int high) throws IllegalArgumentException {
        if (data == null) {
            throw new IllegalArgumentException("null array");
        }
        if (data.length == 0) {
            return -1;
        }
        if (low <= high && (low < 0 || high < 0)) {
            throw new IllegalArgumentException("can't search negative indices");
        }
        if (high > data.length - 1) {
            high = data.length - 1;
        }
        if (low <= high) {
            int mid = (low + high) / 2;
            long midValue = data[mid];
            if (midValue == key) {
                return mid;
            } else if (midValue > key) {
                return binarySearch(data, key, low, mid - 1);
            } else {
                return binarySearch(data, key, mid + 1, high);
            }
        } else {
            return -1;
        }
    }
}

Related

  1. binarySearch(int[] index, int key, int begin, int end)
  2. binarySearch(int[] source, int key)
  3. binarySearch(long[] a, int fromIndex, int toIndex, long key)
  4. binarySearch(long[] a, long key, int endIndex)
  5. binarySearch(long[] array, long key)
  6. binarySearch(Object[] a, Object key)
  7. binarySearch(String[] arr, String value)
  8. binarySearch(String[] array, String sought)
  9. binarySearch(T[] a, T x)