Data Structures and Algorithms-Basic Bisection Algorithm Example

Introduction

Binary search: When sorting an array of non-repeating values, each search can reduce the range by half. And choose the midpoint of this range as the new guess value.

Sample code

public class ArrayTest {
    private static int findIndex(int[] array, int searchValue) {
        //初始下标,初始值为0;
        int initIndex = 0;
        //最大下标,初始值为数组长度-1
        int maxIndex = array.length - 1;
        //二分查找值
        int midIndex;
        //查找次数统计
        int num = 0;
        //遍历
        while (true) {
            num++;
            //初始化二分查找值
            midIndex = (maxIndex + initIndex) / 2;
            //判断相等,则返回下标。
            if (array[midIndex] == searchValue) {
                System.out.println("查找次数:" + num + "次;");
                return midIndex;
                //判断初始值大于最大值时,则查询完成,未找到查询值
            } else if (initIndex > maxIndex) {
                System.out.println("查找次数:" + num + "次;");
                return -1;
            } else {
                //二分查找值大于查找值,将二分查找值下标-1赋值给最大值。
                if (array[midIndex] > searchValue) {
                    maxIndex = midIndex - 1;
                    //否则,将二分查找值+1赋值给初始值。
                } else {
                    initIndex = midIndex + 1;
                }
            }
        }
    }

    public static void main(String[] args) {
        //初始数组,实现二分查找需要数组为有序数组。
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        //定义查找值
        int searchValue = 9;
        //调用查找方法
        int indexValue = ArrayTest.findIndex(array, searchValue);
        if (indexValue == -1) {
            System.out.println("未查询到值:" + searchValue);
        } else {
            System.out.println("查询到值:" + array[indexValue]);
        }
    }
}

result

 

Guess you like

Origin blog.csdn.net/qq_42080073/article/details/108280364