- /*
- Performing Binary Search on Java char Array Example
- This java example shows how to perform binary search for an element
- of java char array using Arrays class.
- */
- import java.util.Arrays;
- public class BinarySearchCharArrayExample {
- public static void main(String[] args) {
- //create char array
- char charArray[] = {'a','b','d','e'};
- /*
- To perform binary search on char array use
- int binarySearch(char[] b, char value) of Arrays class. This method searches
- the char array for specified char value using binary search algorithm.
- Please note that the char array MUST BE SORTED before it can be searched
- using binarySearch method.
- This method returns the index of the value to be searched, if found in the
- array.
- Otherwise it returns (- (X) - 1)
- where X is the index where the the search value would be inserted.
- i.e. index of first element that is grater than the search
- value or array.length, if all elements of an array are less
- than the search value.
- */
- //sort char array using Arrays.sort method
- Arrays.sort(charArray);
- //value to search
- char searchValue = 'b';
- //since 'b' is present in char array, index of it would be returned
- int intResult = Arrays.binarySearch(charArray,searchValue);
- System.out.println("Result of binary search of 'b' is : " + intResult);
- //lets search something which is not in char array !
- searchValue = 'c';
- intResult = Arrays.binarySearch(charArray,searchValue);
- System.out.println("Result of binary search of 'c' is : " + intResult);
- }
- }
- /*
- Output would be
- Result of binary search of 'b' is : 1
- Result of binary search of 'c' is : -3
- */
this site is to help students to learn coding in java platform and qbasic platform. all programs are ICSE and ISC level. Java programs java python Python programs
Performing Binary Search on Java char Array Example
Subscribe to:
Post Comments (Atom)
Second largest number in java using ternary operator
//Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...
-
import java.util.*; class riwi { public static void main(String[]args) { Scanner sc=new Scanner(System.in); System...
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 ...
-
import java.io.*; class snowball { public static void main()throws IOException { BufferedReader br = new BufferedReader(new InputStreamRead...
No comments:
Post a Comment
any problem in any program comment:-