In this post, I am giving an example about implementing Binary Search in Java using characters as data types.
import java.io.*;
public class BinarySearch {
static char[] arr = new char[]{'a','c','f','g','h','q','u','v','w','z'} ;
public static void main (String []args) {
char searchElement = 'q' ;
int lLimit = 0 ;
int uLimit = arr.length ;
traversal (lLimit, uLimit, searchElement) ;
}
public static void traversal (int lLimit, int uLimit, char searchElement) {
int midElement = (lLimit + uLimit) / 2 ;
if (arr[midElement] == searchElement) {
System.out.println(" Element " + searchElement + " found at location: " + midElement) ;
} else if (searchElement < arr[midElement] ) {
traversal(lLimit, midElement,searchElement) ;
} else if (searchElement > arr[midElement] ) {
traversal(midElement, uLimit, searchElement) ;
}
}
}
Output: Element q found at location: 5
No comments:
Post a Comment