Java examples for java.lang:int Array
binary search int array
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { int[] arr = new int[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; int data = 2; binarySearch(arr, data);/*from w w w.j a va 2 s . c om*/ } /** * binary search */ public static void binarySearch(int[] arr, int data) { if (arr.length < 1) { System.out.println("null?"); return; } if (arr.length == 1) { if (data == arr[0]) { System.out.println("success.\t" + data + " -> arr[0]"); return; } else { System.out.println("not in."); return; } } int left = 0; int right = arr.length; while (left <= right) { int mid = (left + right) >> 2; if (data == arr[mid]) { System.out.println("success.\r" + data + " -> arr[" + mid + "]"); return; } if (data < arr[mid]) { right = mid - 1; } else { left = mid + 1; } } System.out.println("not in."); return; } }