二分查找算法

package com.yg.search;/*
@author  Mu_Mu
@date    2020/2/28  15:24
*/

import java.util.ArrayList;
import java.util.List;

public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1, 7, 8, 8,8, 9, 21, 8, 55, 65, 78};
        //int resIndex = binarySearch(arr, 0, arr.length - 1, 8);
        //System.out.println("resIndex:"+resIndex);

        //查找所有值为findVal的序号
        List resIndexList = binarySearchIndexList(arr, 0, arr.length - 1, 8);
        System.out.println("resIndexList:" + resIndexList);
    }

    //查找一个序号
    //二分查找的数组必须为有序序列
    private static int binarySearch(int[] arr, int left, int right, int findVal) {
        //如果没有找到返回-1
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        //用中间值和findVal进行对比
        int tem = arr[mid];
        //如果中间值小于findVal这说明需要查找的值只可能在arr[min]右边,向右递归
        if (arr[mid] < findVal) {
            return binarySearch(arr, mid + 1, right, findVal);
        } else if (arr[mid] > findVal) {
            //如果中间值大于findVal这说明需要查找的值只可能在arr[min]左边,向左递归
            return binarySearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

    //查找所有值为findVal的序号
    private static List<Integer> binarySearchIndexList(int[] arr, int left, int right, int findVal) {
        //如果没有找到返回-1
        if (left > right) {
            return new ArrayList<Integer>();
        }
        int mid = (left + right) / 2;
        //用中间值和findVal进行对比S
        //如果中间值小于findVal这说明需要查找的值只可能在arr[min]右边,向右递归
        if (arr[mid] < findVal) {
            return binarySearchIndexList(arr, mid + 1, right, findVal);
        } else if (arr[mid] > findVal) {
            //如果中间值大于findVal这说明需要查找的值只可能在arr[min]左边,向左递归
            return binarySearchIndexList(arr, left, mid - 1, findVal);
        } else {
            List<Integer> resIndexList = new ArrayList<Integer>();
            int temp = mid - 1;
            //向左遍历找是否还有与findVal相同的元素
            while (temp >= 0 && arr[temp] == findVal) {
                resIndexList.add(temp);
                temp--;
            }
            resIndexList.add(mid);
            //向右遍历找是否还有与findVal相同的元素
            temp=mid+1;
            while (temp <= arr.length-1 && arr[temp] == findVal) {
                resIndexList.add(temp);
                temp++;
            }
            return resIndexList;
        }

    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值