Java examples for Data Structure:Binary Search
Use binary search to locate an item in an array.
import java.security.SecureRandom; import java.util.Arrays; public class Main { public static int binarySearch(int[] data, int key) { int low = 0; // low end of the search area int high = data.length - 1; // high end of the search area int middle = (low + high + 1) / 2; // middle element int location = -1; // return value; -1 if not found do {//from w ww .jav a2s . c o m System.out.print(remainingElements(data, low, high)); for (int i = 0; i < middle; i++) System.out.print(" "); System.out.println(" * "); // indicate current middle // if the element is found at the middle if (key == data[middle]) location = middle; // location is the current middle else if (key < data[middle]) // middle element is too high high = middle - 1; // eliminate the higher half else // middle element is too low low = middle + 1; // eliminate the lower half middle = (low + high + 1) / 2; // recalculate the middle } while ((low <= high) && (location == -1)); return location; } private static String remainingElements(int[] data, int low, int high) { StringBuilder temporary = new StringBuilder(); // append spaces for alignment for (int i = 0; i < low; i++) temporary.append(" "); // append elements left in array for (int i = low; i <= high; i++) temporary.append(data[i] + " "); return String.format("%s%n", temporary); } public static void main(String[] args) { SecureRandom generator = new SecureRandom(); int[] data = new int[15]; // create array for (int i = 0; i < data.length; i++) // populate array data[i] = 10 + generator.nextInt(90); Arrays.sort(data); // binarySearch requires sorted array System.out.printf("%s%n%n", Arrays.toString(data)); // display array int searchInt = 123; // perform search int location = binarySearch(data, searchInt); if (location == -1) // not found System.out.printf("%d was not found%n%n", searchInt); else // found System.out.printf("%d was found in position %d%n%n", searchInt, location); } }