1. package algorithm;  
  2.  
  3. public class Search {  
  4.  
  5. public static void main(String[] args) {  
  6. int[] array = { 20, 44, 48, 55, 62, 66, 74, 88, 93, 99 };  
  7. int result = binarySearch(90, array);  
  8. System.out.println(result);  
  9. }  
  10.  
  11. //基本类型的线性查找  
  12. public static int linearSearch(int target, int[] array) {  
  13. for (int i = 0; i < array.length; i++) {  
  14. if (array[i] == target)  
  15. return i;  
  16. }  
  17. return -1;  
  18. }  
  19.  
  20. //对象的情况的线性查找  
  21. public static int linearSearch(Object target, Object[] array) {  
  22. for (int i = 0; i < array.length; i++) {  
  23. if (array[i].equals(target))  
  24. return i;  
  25. }  
  26. return -1;  
  27. }  
  28.  
  29. //基本类型的二分查找  
  30. public static int binarySearch(int target, int[] array) {  
  31. int low = 0;  
  32. int high = array.length - 1;  
  33. while (low <= high) {  
  34. int middle = (low + high) / 2;  
  35. if (array[middle] == target) {  
  36. return middle;  
  37. else if (array[middle] < target) {  
  38. low = middle + 1;  
  39. else 
  40. high = middle - 1;  
  41. System.out.println("low=" + low);  
  42. System.out.println("high=" + high);  
  43. System.out.println("middle=" + middle);  
  44. System.out.println("====================");  
  45. }  
  46. return -1;  
  47. }  
  48.  
  49. //对象情况下的二分查找  
  50. public static int binarySearch(Object target, Object[] array) {  
  51. int low = 0;  
  52. int high = array.length - 1;  
  53. while (low <= high) {  
  54. int middle = (low + high) / 2;  
  55. int result = ((Comparable) array[middle]).compareTo(target);  
  56. if (result == 0) {  
  57. return middle;  
  58. else if (result < 0) {  
  59. low = middle + 1;  
  60. else 
  61. high = middle - 1;  
  62. }  
  63. return -1;  
  64. }  

结果:

low=5
high=9
middle=4
====================
low=8
high=9
middle=7
====================
low=8
high=7
middle=8
====================
-1