Java Binary Search binarySearch(byte[] a, int key)

Here you can find the source of binarySearch(byte[] a, int key)

Description

Search for a big-endian 4-byte integer in a array of bytes.

License

Apache License

Parameter

Parameter Description
a array of containing only big-endian 4-byte integers.
key the value to seach for.

Return

the index found.

Declaration

public static int binarySearch(byte[] a, int key) 

Method Source Code

//package com.java2s;
/**/*from  www. j  ava2  s.com*/
 * 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.
 */

public class Main {
    /**
     * Search for a big-endian 4-byte integer in a array of bytes.
     *
     * @param a array of containing only big-endian 4-byte integers.
     * @param key the value to seach for.
     * @return the index found.
     */
    public static int binarySearch(byte[] a, int key) {
        int low = 0;
        int high = a.length;

        while (low < high) {
            int mid = (low + high) >>> 1;
            if (mid % 4 != 0) {
                if (high == a.length) {
                    mid = low;
                } else {
                    mid = high;
                }
            }
            int midVal = getInt(a, mid);

            if (midVal < key)
                low = mid + 4;
            else if (midVal > key)
                high = mid - 4;
            else
                return mid; // key found
        }
        if (low == a.length) {
            return low;
        }
        return key > getInt(a, low) ? low + 4 : low;

    }

    public static int getInt(final byte[] b, final int offset) {
        return (b[offset + 0] & 0xFF) << 24 | (b[offset + 1] & 0xFF) << 16 | (b[offset + 2] & 0xFF) << 8
                | (b[offset + 3] & 0xFF) << 0;
    }
}

Related

  1. binarySearch(byte[] a, byte key, int startPos)
  2. binarySearch(byte[] readBuffer, int offset, int length, byte value)
  3. binarySearch(char[] arr, int key)
  4. binarySearch(double experience, int min, int max)
  5. binarySearch(double values[], double search)