Binary Search

 1 import java.util.*;

 2 

 3 public class BinarySearch {

 4     

 5     public static final int NO_SUCH_KEY = -1;    

 6     

 7     public static int search(int[] keys, int key) {

 8         if(keys == null || keys.length == 0) 

 9             return NO_SUCH_KEY;

10 

11         return searchImpl(keys, key, 0, keys.length - 1);

12     }

13 

14     private static int searchImpl(int[] keys, int key, int low, int high) {

15         if(low > high) return NO_SUCH_KEY;

16         

17         int mid = (low + high) /2;

18         if(key == keys[mid])

19             return mid;

20         else if(key < keys[mid])

21             return searchImpl(keys, key, low, mid - 1);

22         else 

23             return searchImpl(keys, key, mid + 1, high);

24     }

25 

26     public static void main(String[] args) {

27         int[] keys = new int[10];

28         Random rand = new Random();

29         for(int i = 0; i < keys.length; i++) {

30             keys[i] = rand.nextInt() % 1000;

31         }

32         Arrays.sort(keys);

33         System.out.println(Arrays.toString(keys));

34 

35         Scanner sc = new Scanner(System.in);

36         int k;

37         while(true) {

38             k = sc.nextInt();

39             int i = search(keys, k);

40             

41             if(i == NO_SUCH_KEY) {

42                 System.out.println("Not found, would exit.");

43                 break;

44             } else {

45                 System.out.println("Found, position:" + i);

46             }

47         }

48     }

49 }

 

你可能感兴趣的:(Binary search)