Java--二分法查找

package com.company;

import java.util.Scanner;

public class Main {

    int search(int a[],int number)
    {
        int high = a.length-1;
        int mid = 0;
        int low = 0;
        while (low <= high)
        {
            mid=(high+low)/2;
            if(a[mid]>number)
            {
                high = mid-1;
            }
            else if(a[mid]<number)
            {
                low = mid+1;
            }
            else
            {
                return mid;
            }
        }
        return  -1;

    }

    public static void main(String[] args) {
    // write your code here
        int []b= new int [7] ;
        int num  ;
        int t ;
        Main s = new Main();
        Scanner scan = new Scanner(System.in);
        for(int i = 0;i<b.length;i++)
        {
            b[i] = scan.nextInt();
        }
        num  = scan.nextInt();
        for(int i = 0;i<b.length-1;i++)
        {
            for(int j = i+1;j<b.length;j++)
            {
                if(b[i]>b[j])
                {
                    t=b[i];
                    b[i]=b[j];
                    b[j]=t;

                }
            }

        }

        System.out.println(s.search(b,num));


    }
}

 

posted @ 2020-12-21 22:54  zhou小月  阅读(112)  评论(0编辑  收藏  举报