歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java針對數組的普通查找法和二分查找法

Java針對數組的普通查找法和二分查找法

日期:2017/3/1 10:26:17   编辑:Linux編程
下面是針對數組的普通查找法和二分查找法的示例代碼
  1. package com.jadyer.sort;
  2. /**
  3. * 數組查找方式
  4. * @detail 這裡演示了普通查找法和二分查找法
  5. */
  6. public class ArraySearch {
  7. public static void main(String[] args) {
  8. int commonResult = commonSearch(new int[]{1,5,6,7,4,3,9,11,13,14,16,19,21}, 9);
  9. int binaryResult = binarySearch(new int[]{1,3,4,6,7,8,9,12,15,17,18,20,22}, 8);
  10. System.out.println("二分查找法: " + binaryResult);
  11. System.out.println("普通查找法: " + commonResult);
  12. }
  13. /**
  14. * 普通查找法
  15. * @detail 該方式最好理解,同時效率也最低
  16. */
  17. public static int commonSearch(int[] array, int value){
  18. for(int i=0; i<array.length; i++){
  19. if(value == array[i]){
  20. return i; //返回該元素在數組中的下標
  21. }
  22. }
  23. return -1; //不存在該元素則返回-1
  24. }
  25. /**
  26. * 二分查找法
  27. * @detail 要求數組有序,升序或降序均可
  28. */
  29. public static int binarySearch(int[] array, int value){
  30. int low = 0; //最小元素值的下標
  31. int high = array.length - 1; //最大元素值的下標
  32. int middle; //中間元素的下標
  33. while(low <= high){
  34. middle = (low+high) / 2;
  35. for(int i=0; i<array.length; i++){
  36. System.out.print(array[i]);
  37. if(i == middle){
  38. System.out.print("#"); //在元素後面用#號標識其為中間元素
  39. }
  40. System.out.print(" "); //各元素間用空格隔開
  41. }
  42. System.out.println();
  43. if(value == array[middle]){
  44. return middle;
  45. }
  46. if(value < array[middle]){
  47. high = middle - 1; //右側的不要了
  48. }
  49. if(value > array[middle]){
  50. low = middle + 1; //左側的不要了
  51. }
  52. }
  53. return -1; //不存在該元素則返回-1
  54. }
  55. }
Copyright © Linux教程網 All Rights Reserved