3:05 pm - Monday January 16, 2017

Creating Program for Searches the specified array of chars for the specified value using binarySearch(char[] a, char 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

This Creating Program for Searches the specified array of chars for the specified value using the binary search algorithm

EXAMPLE PROGRAM


import java.util.*;

public class ArrayBinSrchChar {

	public static void main(String[] args) {

		char array[] = { 'm', 'a', 'd', 'h', 'n' };

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

		for (char i : array) {

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

		}

		Arrays.sort(array);

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

		for (char i : array) {

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

		}

		char search = 'h';

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

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

	}

}

Output

Before Array:

Character=m

Character=a

Character=d

Character=h

Character=n

After Array:

Character=a

Character=d

Character=h

Character=m

Character=n

The Index Value h placed in:2

 

Explanation

 

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

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

 

Parameters:

a – the array to be searched

key – the value to be searched for

 

Returns:

index of the search key, if it is contained in the array; 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 greater than the key, or a.length if all elements in the array 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.

BACK

 

Filed in: Z-A All Java Codes

Comments are closed.