If tomorrow never comes

The meaning of life is creation,which is independent an boundless.

导航

二分查找

Posted on 2009-05-18 16:55  Brucegao  阅读(336)  评论(0编辑  收藏  举报
二分查找

1、二分查找(Binary Search)
二分查找又称折半查找,它是一种效率较高的查找方法。
二分查找要求:线性表是有序表,即表中结点按关键字有序,并且要用向量作为表的存储结构。不妨设有序表是递增有序的。

2、二分查找的基本思想
二分查找的基本思想是:(设R[low..high]是当前的查找区间)
(1)首先确定该区间的中点位置:

(2)然后将待查的K值与R[mid].key比较:若相等,则查找成功并返回此位置,否则须确定新的查找区间,继续二分查找,具体方法如下:
①若R[mid].key>K,则由表的有序性可知R[mid..n].keys均大于K,因此若表中存在关键字等于K的结点,则该结点必定是在位置mid左边的子表R[1..mid-1]中,故新的查找区间是左子表R[1..mid-1]。
②类似地,若R[mid].key
因此,从初始的查找区间R[1..n]开始,每经过一次与当前查找区间的中点位置上的结点关键字的比较,就可确定查找是否成功,不成功则当前的查找区间就缩小一半。这一过程重复直至找到关键字为K的结点,或者直至当前的查找区间为空(即查找失败)时为止。

3、二分查找算法(C#)

 

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

namespace MidSeach
{
    
class Program
    
{
        
/// <summary>
        
/// Binary search method
        
/// </summary>
        
/// <param name="list"></param>
        
/// <param name="position"></param>
        
/// <returns></returns>

        public static int  MidleSearch(int[] list,int position)
        
{
            
//int mid = position;
            int low = 1;
            
int high = list.Length;

            
while (low <= high)
            
{
                
int mid=(low+high)/2;
                
if (position == list[mid])
                
{
                    
return mid;
                }

                
else
                
{
                    
if (position < list[mid])
                    
{
                        high 
= mid -1;
                    }

                    
else
                    
{
                        low 
= mid +1;
                    }

                }

            }


            
return -1;
        }

        
static void Main(string[] args)
        
{
            
int[] list = new int[10];
            
for (int i = 0; i < 10; i++)
            
{
                Console.Write(
"input 10 numbers,here is the {0}th number:",i);
                list[i] 
= Convert.ToInt32(Console.ReadLine());
            }


            Console.WriteLine(
"Find a number in the list");
            
int find = Convert.ToInt32(Console.ReadLine());
            
int result = MidleSearch(list, find);
            Console.WriteLine(
"The result is {0}", result);
            Console.ReadLine();
            Console.ReadLine();
        }

    }

}