当前位置 : 主页 > 编程语言 > java >

折半查找

来源:互联网 收集:自由互联 发布时间:2021-06-28
折半查找 package 实验四;import java.util.Scanner;/* * author:黄良运 * time:2017.12.6 * 折半查找 */public class Find {public int search(AnyType Arr[], AnyType x) {int mid, low, high;low = 0;high = Arr.length - 1;while (low =
折半查找
package 实验四;

import java.util.Scanner;
/*
 * author:黄良运
 * time:2017.12.6
 * 折半查找
 */
public class Find
 
  > {

	public int search(AnyType Arr[], AnyType x) {
		int mid, low, high;
		low = 0;
		high = Arr.length - 1;
		while (low <= high) {
			mid = (low + high) / 2;
			System.out.println("mid: "+mid+" low: "+low+" high: "+high);
			if (Arr[mid].compareTo(x) == 0)
				return mid;
			else if (Arr[mid].compareTo(x) > 0)
				high = mid - 1;
			else
				low = mid + 1;
		}
		return -1;
	}
	
	public static void main(String []y){
		Scanner in  = new Scanner(System.in);
		Integer Arr[] = {5,14,18,21,23,29,31,35};
		Find
  
    find = new Find
   
    (); System.out.println(find.search(Arr, 23)+": "+Arr[find.search(Arr, 23)]); } }
   
  
 
网友评论