Java—折半查找法

折半查找法在计算机科学中,折半搜索(英语:half-interval search),也称二分搜索(英语:binary search)、对数搜索(英语:logarithmic search),是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半

      简单的说,折半查找法就是把数组每次都在中间斩断,用中间的数与您想要查找的数做比较,然后确定要查找的数的位置。

      所以,折半查找法有一个最重要的前提就是数组中的数据是有序的。

Java代码:

public class Demo {
public static void main(String[] args){
         Scanner cin = new Scanner(System.in);  //此处需要导包      import java.util.Scanner;
         String[] str=new String[2];
         for(int i=0;i<2;i++){
             str[i] = cin.nextLine();
         }        
         String[] st = str[0].split(" ");
         int[] c = new int[st.length];
         for(int i=0;i<c.length;i++){
             c[i]=Integer.parseInt(st[i]);
         }
         int key = Integer.parseInt(str[1]);
         int result = search(c,key);
         System.out.print(result+1);            //找到返回相应索引值(从1开始),没找到返回1
     }
     public static int search(int[] R,int k){
        int length = R.length;
         int mid,low=0,high=length;
         while(low<=high){
             mid = (low+high)/2;
             if(R[mid]==k){
                 return mid;
             }else if(R[mid]>k){
                high=mid-1;
            }else{
                 low=mid+1;
            }
        }
         return -1;
     }

}


比如输入  2 4 6 8 10 12 14 16 
然后输入要查找的数字,比如  8
就会输出    4



猜你喜欢

转载自blog.csdn.net/DJGXGG/article/details/80375388