1. 程式人生 > >二分搜尋(非遞迴)

二分搜尋(非遞迴)

 1 public class Main{
 2     public static int binarySearch(int a[],int x,int n) {
 3         int left=0;
 4         int right=n-1;
 5         while(left<=right) {
 6             int middle=(left+right)/2;
 7             if(a[middle]==x) {
 8                 return middle;
 9             }
10             if
(a[middle]<x) { 11 left=middle+1; 12 } 13 else { 14 right=middle-1; 15 } 16 } 17 return -1; 18 } 19 public static void main(String args[]) { 20 int a[]= {1,3,5,7,9}; 21 System.out.println(binarySearch(a,7,a.length));
22 } 23 }