首页 > 其他 > 详细

二分搜索找到所在区间

时间:2014-03-18 12:20:39      阅读:267      评论:0      收藏:0      [点我收藏+]

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

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

bubuko.com,布布扣
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;
        }
    }
}
bubuko.com,布布扣

二分搜索找到所在区间,布布扣,bubuko.com

二分搜索找到所在区间

原文:http://www.cnblogs.com/liquadli/p/3604799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!