查找算法
基本查找
package MyApi.search;public class a01BasicSearchdemo01 {public static void main(String[] args) {
int[] arr={131,127,147,81,103,23,7,79};
int number=82;System.out.println(BasicSearch(arr,number));}public static boolean BasicSearch(int[] arr,int number){for (int i = 0; i < arr.length; i++) {if(arr[i]==number){return true;}}return false;}
}
二分查找
1.min和max表示当前要查找的范围
2.mid是在min和max的中间
3.如果要查找的元素在mid的左边,缩小范围时,min不变,max等于mid减一
4.如果要查找的元素在mid的右边,缩小范围时,max不变,min等于mid加一。
package MyApi.search;public class a02BinarySearch {public static void main(String[] args) {int[] arr={131,127,81,79,7};int number=82;System.out.println(binarySearch(arr,82));}public static int binarySearch(int[]arr,int number){int min=0;int max= arr.length-1;
while(true){if(min>max){return -1;}int mid=(min+max)/2;if(arr[mid]>number){max=mid-1;}else if(arr[mid]<number){
min=mid+1;}else{return mid;}
}}
}