• 二分查找法


    代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace TwoSearch
    {
        
    class Data
        {
            
    int[] list;
            
    int lower; 
            
    int upper; 
            
    int middle;

            
    int count = 0//记录比较次数

            
    public Data(int max)
            {
                list 
    = new int[max];

                
    for (int i = 0; i < max; i++)
                {
                    list[i] 
    = i;
                }

                lower 
    = 0;

                upper 
    = list.Length - 1;
            }

            
    public int Find(int t)
            {
                
    while (lower <= upper) //必须要有"="号,否则某些数字可以查找,但无法输出
                {
                    count 
    = count + 1
                    middle 
    = (lower + upper) / 2;
                    
    if (t == list[middle])
                        
    return middle;
                    
    else if (t > list[middle])
                        lower 
    = middle + 1; //变更起始位置
                    
    else
                        upper 
    = middle; //变更总长度
                }
                    
    return -1//没找到
      
            }

            
    public void GetCount()
            {
                Console.WriteLine(
    "比较次数:" + count);
            }

            
    public void Size()
            {
                Console.WriteLine(
    "数组长度:"+upper);
            }

            
    /// <summary>
            
    /// 各项数组值
            
    /// </summary>
            public void Display()
            {
                
    for (int i = 0; i < upper; i++)
                {
                    Console.WriteLine(
    "值:"+list[i]);
                }
                Console.ReadLine();
            }
        }

        
    class Program
        {
            
    static void Main(string[] args)
            {
                
    //此处注意数值不能越界
                Data data = new Data(100000);

                Console.WriteLine(
    "查找数字:"+data.Find(6));
                data.GetCount();
                data.Size();
                data.Display();
            }
        }
    }
  • 相关阅读:
    ural 1723 Sandro's Book
    ural 1104 Don’t Ask Woman about Her Age
    ural 1052 Rabbit Hunt
    ural 1837 Isenbaev's Number
    ural 1348 Goat in the Garden 2
    ural 1207 Median on the Plane
    ural 1640 Circle of Winter
    段错误 核心已转储尝试解决
    显卡相关命令介绍【转载】
    Linux的top命令学习【转载】
  • 原文地址:https://www.cnblogs.com/scotly/p/1718716.html
Copyright © 2020-2023  润新知