欢迎来到萧静默的博客

书山有路勤为径,学海无涯苦作舟。

JAVA-二分法查找

package learn.arrary;

import java.awt.Label;
import java.util.Random;
import java.util.Scanner;

public class arrary
{
    public static void main(String[] args)
    {
        array arr = new array();
        arr.arry();
        System.out.println();
        System.out.println("************************************************************************");
        int temp;
        // 二分法之前先进行排序
        for (int i = 0; i < arr.array.length; i++)
        {
            for (int j = i; j < arr.array.length; j++)
            {
                temp = arr.array[i];
                if (arr.array[i] > arr.array[j])// 从小到大排序
                {
                    arr.array[i] = arr.array[j];
                    arr.array[j] = temp;
                }
            }
        }
        for (int i : arr.array)
        {
            System.out.print(i + "\t");
        }
        System.out.println();
        System.out.println("************************************************************************");
        int search;
        System.out.println("请输入你要猜测的数据");
        input inp = new input();
        search = inp.inputNum();
        int head = 0, end = arr.array.length - 1;// 初始首索引和末索引
        boolean isflag = true;
        boolean isflag1 = true;
        while (head <= end)
        {
            int middle = (head + end) / 2;
            if (search == arr.array[middle])
            {
                System.out.println("找到指定目标,元素位置为" + middle);
                isflag = false;
                // isflag1 = false;
                break;
            } else if (search < arr.array[middle])
            {
                end = middle - 1;
            } else if (search > arr.array[middle])
            {
                head = middle + 1;
            }
        }
        if (isflag)
        {
            System.out.println("很遗憾,没找到哦啊哦");
        }
    }
}

class array// 生成随机数类
{
    int[] array = new int[100];

    public void arry()
    {
        Random random = new Random();

        for (int i = 0; i < array.length; i++)
        {
            array[i] = random.nextInt(100);
        }
        for (int i : array)
        {
            System.out.print(i + "\t");
        }
    }
}

class input
{
    int a;
    Scanner scanner = new Scanner(System.in);

    int inputNum()
    {
        a = scanner.nextInt();
        return a;
    }
}

 

 看看怎么改编成如果猜不中 继续猜测的程序?

posted @ 2020-04-21 09:43  萧静默  阅读(281)  评论(0编辑  收藏  举报