加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 安全 > 正文

算法系列15天速成 第五天 五大经典查找【中】

发布时间:2020-03-14 19:09:38 所属栏目:安全 来源:站长网
导读:大家可否知道,其实查找中有一种O(1)的查找,即所谓的秒杀

static void Main(string[] args)
        {
            Console.WriteLine("原数据为:" + string.Join(",", students));


            int value = 205;

Console.WriteLine("n插入数据" + value);

//将205插入集合中,过索引
            var index = insert(value);

//如果插入成功,获取205元素所在的位置
            if (index == 1)
            {
                Console.WriteLine("n插入后数据:" + string.Join(",", students));
                Console.WriteLine("n数据元素:205在数组中的位置为 " + indexSearch(205) + "位");
            }

Console.ReadLine();
        }

///<summary>
/// 学生主表
///</summary>
        static int[] students = {
                                   101,102,103,104,105,0,0,0,0,0,
                                   201,202,203,204,0,0,0,0,0,0,
                                   301,302,303,0,0,0,0,0,0,0
                                };
        ///<summary>
///学生索引表
///</summary>
        static IndexItem[] indexItem = {
                                  new IndexItem(){ index=1, start=0, length=5},
                                  new IndexItem(){ index=2, start=10, length=4},
                                  new IndexItem(){ index=3, start=20, length=3},
                                };

///<summary>
/// 查找数据
///</summary>
///<param></param>
///<returns></returns>
        public static int indexSearch(int key)
        {
            IndexItem item = null;

// 建立索引规则
            var index = key / 100;

//首先去索引找
            for (int i = 0; i < indexItem.Count(); i++)
            {
                if (indexItem[i].index == index)
                {
                    item = new IndexItem() { start = indexItem[i].start, length = indexItem[i].length };
                    break;
                }
            }

//如果item为null,则说明在索引中查找失败
            if (item == null)
                return -1;

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读