1:40 am - Wednesday February 22, 2017

Program for Searches a range of the specified array of bytes for the specified value using the binarySearch(byte[] a, int fromIndex, int toIndex, byte key)

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

Program for Searches a range of the specified array of bytes for the specified value using the binary search algorithm.

EXAMPLE PROGRAM


import java.util.*;

public class ArrayBinSrch4el {

	public static void main(String[] args) {

		byte array[] = { 70, 50, 90, 30, 40, 10 };

		System.out.println("Before Array: ");

		for (byte i : array) {

			System.out.println("Number=" + i);

		}

		Arrays.sort(array);

		System.out.println("After Array: ");

		for (byte i : array) {

			System.out.println("Number=" + i);

		}

		byte search = 40;

		int get = Arrays.binarySearch(array, 2, 6, search);

		System.out.println("The Index Value 30 placed in:" + get);

	}

}

Output

Before Array:

Number=70

Number=50

Number=90

Number=30

Number=40

Number=10

After Array:

Number=10

Number=30

Number=40

Number=50

Number=70

Number=90

The Index Value 30 placed in:2

 

Explanation

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

Searches a range of the specified array of bytes for the specified value using the binary search algorithm. The range must be sorted (as by the sort(byte[], int, int) method) prior to making this call. If it is not sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.

Parameters:

a – the array to be searched

fromIndex – the index of the first element (inclusive) to be searched

toIndex – the index of the last element (exclusive) to be searched

key – the value to be searched for

 

Returns:

index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

 

Throws:

IllegalArgumentException – if fromIndex > toIndex

ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length

 

Since:

1.6

BACK

Filed in: Z-A All Java Codes

Comments are closed.