博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二分搜索找到所在区间
阅读量:7106 次
发布时间:2019-06-28

本文共 2339 字,大约阅读时间需要 7 分钟。

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

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

你可能感兴趣的文章
IE的坏脾气——3像素Bug
查看>>
PHP+Oracle Instant Client
查看>>
Linux创建LVM
查看>>
VirtualBox开发环境的搭建详解(转)
查看>>
C进阶 - 内存四驱模型
查看>>
React
查看>>
音乐格式转换器哪个好
查看>>
FFMPEG vaapi_encoder 源码阅读
查看>>
支付-收款
查看>>
vue项目打包后想发布在apache www/vue 目录下
查看>>
MixPHP 独特的SQL构建方式
查看>>
丁香园开源接口管理系统
查看>>
[LeetCode] Remove Element
查看>>
ConcurrentHashMap源码分析_JDK1.8版本
查看>>
竹翎(Material风格的APP,附源码)
查看>>
API数据格式转换方法学习
查看>>
精益业务分析宣言解读
查看>>
装修红宝书
查看>>
swiper 划不动问题
查看>>
Inferno 7.1.12 发布,类 React 的高性能用户界面库
查看>>