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

    二分查找又称折半查找

    算法基本思想

    首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。


    优点

    比较次数少,查找速度快,平均性能好;

    缺点

    要求待查表为有序表,且插入删除困难。

    因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

    算法复杂度

    假设其数组长度为n,其算法复杂度为o(log(n))


    // BinarySearch.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    
    int BinarySearch(int* in, int startpos, int endpos, int obj);
    int _tmain(int argc, _TCHAR* argv[])
    {
    	int a[8] = { 2, 3, 5, 7, 9, 10, 13, 56 };
    	cout << BinarySearch(a, 0, 7, 10)<<endl;
    	system("pause");
    	return 0;
    }
    
    int BinarySearch(int* in,int startpos, int endpos, int obj)
    {
    	_ASSERTE(endpos >= startpos);
    	if (startpos == endpos)
    		if (in[startpos] == obj)
    			return startpos;
    		else
    			return-1;
    	if (endpos - startpos == 1)
    		if (in[startpos] == obj )
    			return startpos;
    		else if (in[endpos] == obj)
    			return endpos;
    		else
    			return-1;
    	int k1;
    	
    	k1 = (startpos + endpos) / 2;
    	if (in[k1] == obj)
    		return k1;
    	if (in[k1]>obj)
    		BinarySearch(in, startpos, k1 - 1,obj);
    	else
    		BinarySearch(in, k1+1, endpos, obj);
    }


    版权声明:

  • 相关阅读:
    小的面试题
    email
    网络
    进程,线程
    周日作业
    Python_day9
    Python_day8
    假期作业
    12/13
    Python_day7
  • 原文地址:https://www.cnblogs.com/walccott/p/4956913.html
Copyright © 2011-2022 走看看