zoukankan      html  css  js  c++  java
  • 二分查找的思路

    关于二分查找,一直稀里糊涂,终于在看了一些资料后,总结出一个比较实用的记法。

    总的原则为,区间规则形式一样,区间之间不重复,不漏值。

    令待查数组为source[],数组维数为size,要查的的数位key.

    区间划分的原理:1、左闭右闭的划分法[ )

                               head=0,tail=size,mid=(head+tail)/2;

                               总区间为[0,size)

                               开始查找,if(key<source[mid]),则在前半部查找,区间令为[head,mid);即tail=mid

                                             if(key==source[mid]),则值已找到,  区间为   [mid,mid)

                                             if(key>source[mid]),则在后半部查找,区间令为[mid+1,tail);即head=mid+1

                               以上这三个部分的区间正好合为整个待查区间。

                         2、左闭右闭的划分法[ ]

                               head=0,tail=size-1,mid=(head+tail)/2;

                               总区间为[0,size-1]

                               开始查找,if(key<source[mid]),则在前半部查找,区间令为[head,mid-1];即tail=mid-1

                                             if(key==source[mid]),则值已找到,  区间为   [mid,mid]

                                             if(key>source[mid]),则在后半部查找,区间令为[mid+1,tail];即head=mid+1

                               以上这三个部分的区间正好合为整个待查区间。

    这样是不是很好记了呢?

    以下是C#实现[]形式的代码:

    View Code
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace binary_search
    {
        class Program
        {
           static int search(int[] source, int size, int key)
            {
                int head = 0;
                int tail = size - 1;
                int mid = (head + tail) / 2;
                int flag = 0;//用于标记能否查询到
                while (head <=tail) 
                {
                    mid = (head + tail) / 2;
                    if (source[mid] < key)
                    {
                        head = mid + 1;                  
                    }
                    else if (source[mid] > key)
                    {                  
                        tail = mid -1;           
                    }
                    else if (source[mid] == key)
                    { 
                        flag = 1;
                        break;
                    }
                } 
                if (flag==1)
                    Console.WriteLine("{0}在目标数组的第{1}个位置", key, mid+1);
                else
                    Console.WriteLine("{0}在目标数组中找不到", key);
    
                return 0;
    
            }
            static void Main(string[] args)
            {
                int[] a ={ 1, 2, 3, 4, 5,6 };
                int size = 6;
                int key = 4;
                search(a, size, key);
                Console.Read();
            }
        }
            
    }
  • 相关阅读:
    2021年1月4号
    2021年1月3号
    2021年1月2日
    2021年1月1日
    Jenkins定时构建与轮询SCM
    2017-08-22校验
    2017-08-21xlVBASplitSheetsSameTime
    20170821xlVBA跨表公式套用
    20170821xlVBA隐藏空行
    20170814xlVBA限定日期按客户分类汇总
  • 原文地址:https://www.cnblogs.com/huang1990/p/2995284.html
Copyright © 2011-2022 走看看