二分搜索找到所在区间

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

比如,对于数组“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;
        }
    }
}

 

posted @ 2014-03-17 12:22  lqj_piaohong  阅读(164)  评论(0编辑  收藏  举报