zoukankan      html  css  js  c++  java
  • 二分查找——算法系列

    二分查找有两个条件:

    1. 数组必须有序,无序数组查找之前需要先让其有序
    2. 只限于顺序存储结构

    代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Net;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> list = new List<int>();
                for (int i = 0; i < 2000; i++)
                {
                    Thread.Sleep(1);
                    list.Add(new Random((int)DateTime.Now.Ticks).Next(0, 100));
                }
                list.OrderBy(single => single).ToList();
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(100);
                    if (BinarySearch(list, i) == 1)
                        Console.WriteLine("找到了");
                    else
                        Console.WriteLine("没找到");
                }
                
                Console.ReadLine();
            }
    
            public static int BinarySearch(List<int> list, int key)
            {
                int low = 0;
                int high = list.Count - 1;
                while (low <= high)
                {
                    int middle = (low + high) / 2;
                    if (key == list[middle])
                        return 1;
                    else if (key > list[middle])
                        low = middle + 1;
                    else
                        high = middle - 1;
                }
                return 0;
            }
        }
    }
  • 相关阅读:
    前端资源分享
    解决COM组件80070005错误
    【迁移】—Entity Framework实例详解 转
    IIS错误处理集合
    疯狂蚂蚁框架搭建
    MSSQL日期格式化
    一句SQL实现获取自增列操作
    mongodb 性能篇
    mongodb管理篇
    mongodb高级应用
  • 原文地址:https://www.cnblogs.com/7ants/p/2961064.html
Copyright © 2011-2022 走看看