查找算法
1、线性查找
2、二分查找
PS:后续或有更新
1 public class Search { 2 3 /** 4 *线性查找方法 5 **/ 6 public static int linearSearch(int[] obj, int value) { 7 int i; 8 int result; 9 for (i = 0; i < obj.length; ++i) { 10 if (value == obj[i]) { 11 break; 12 } 13 } 14 if (i == obj.length) { 15 result = -1; 16 } else { 17 result = i; 18 } 19 return result; 20 } 21 22 /** 23 *二分查找方法 24 **/ 25 public static int binarySearch(int[] obj, int value) { 26 int middle = 0; 27 int low = 0; 28 int top = obj.length + 1; 29 //System.out.println(low +" " + middle +" " + top); 30 31 while (true) { 32 middle = (low + top) / 2; 33 if (value == obj[middle]) { 34 return middle; 35 } else if (low > top) { 36 return -1; 37 } else { 38 if (value < obj[middle]) { 39 top = middle - 1; 40 } else { 41 low = middle + 1; 42 } 43 } 44 //System.out.println(low +" " + middle +" " + top); 45 } 46 } 47 48 /** 49 *显示数据方法 50 **/ 51 public static void display(int[] obj) { 52 System.out.print("["); 53 for (int i = 0; i < obj.length; ++i) { 54 System.out.print(obj[i]); 55 if (i != obj.length - 1) { 56 System.out.print(","); 57 } 58 } 59 System.out.println("]"); 60 61 } 62 public static void main(String[] args) { 63 int[] nums = new int[]{10, 2, 22, 4, 59, 99}; 64 Search.display(nums); 65 66 System.out.println(Search.linearSearch(nums, 2)); 67 68 System.out.println(Search.binarySearch(nums, 10)); 69 System.out.println(Search.binarySearch(nums, 2)); 70 System.out.println(Search.binarySearch(nums, 22)); 71 System.out.println(Search.binarySearch(nums, 4)); 72 System.out.println(Search.binarySearch(nums, 59)); 73 System.out.println(Search.binarySearch(nums, 99)); 74 75 76 } 77 }
valuestack

浙公网安备 33010602011771号