二分搜索找到所在区间

找出给定整数在一个有序数组中的区间。

比如,对于数组“1,3,5,7,10”,给定“2”,找到它在“3”和“5”区间内。要求用二分搜索。时间控制在log2n内。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[] { 1, 3, 5, 7, 10, 11, 13, 15, 17 };

            for (int i = 1; i <= 17; ++i)
            {
                int left = -1;
                int right = -1;
                biSearch(a, i, out left, out right);

                int l = -1;
                int r = -1;
                sequenceSearch(a, i, out l, out r);

                Console.WriteLine(string.Format("Search {0}, Index: {1}-{2}, Value: {3}-{4}, TestResult: {5}",
                    i,
                    left, right,
                    a[left], a[right],
                    left == l && right == r));
            }
        }

        static bool biSearch(int[] a, int t, out int left, out int right)
        {
            left = -1;
            right = a.Length;

            int n = a.Length;
            int l = 0; int b = n - 1;

            int m = -1;
            while (l <= b)
            {
                m = (l + b) / 2;

                if (a[m] < t)
                {
                    l = m + 1;
                    left = m;
                }
                else if (a[m] == t)
                {
                    left = m;
                    right = m;
                    return true;
                }
                else //a[m] > t
                {
                    b = m - 1;
                    right = m;
                }
            }

            return left >= 0 && right < a.Length;
        }

        static bool sequenceSearch(int[] a, int t, out int right, out int left)
        {
            right = -1;
            left = a.Length;

            for (int i = 0; i < a.Length; ++i)
            {
                if (a[i] < t)
                {
                    right = i;
                }
                else if (a[i] > t)
                {
                    left = i;
                    return right >= 0;
                }
                else //a[i]==i
                {
                    left = i;
                    right = i;
                    return true;
                }
            }

            return left < a.Length;
        }
    }
}

 

转载于:https://www.cnblogs.com/liquadli/p/3604799.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值