二分查找/折半查找

package practice;
import java.util.Scanner;
public class 二分查找 {
    public static int[] maopao(int[] args) {//可以接收也可以不接收
for (int i = 0; i < args.length; i++) {
for (int j = 0; j < args.length - 1 - i; j++) {
if (args[j] > args[j + 1]) {
    int temp = args[j];
    args[j] = args[j + 1];
    args[j + 1] = temp;
                }
            }
    }
    return args;
}
    public static void main(String [] args) {
        int []a= {20,33,12,88,76,23};
        a=maopao(a);
        for(;;) {
        Scanner scanner=new Scanner(System.in);
        int t=scanner.nextInt();
        int f=0;
        int l=a.length-1;
        int m=0;
        while(true) {
            
            m=(l+f)/2;
            if(t==a[m]) {
                System.out.println("找到");
                break;
            }
            else {
                if (t>a[m]) {
                    f=m+1;
                    
                }else {
                    l=m-1;
                }
            }
            if (f>l) {
                System.out.println("没找到");
                break;
                 }
               }
             }
          }
    }
    
    
    
    
    
    


 

猜你喜欢

转载自blog.csdn.net/weixin_42194284/article/details/89609032