二叉树的查找设计

来源:互联网 发布:电信网络转换 编辑:程序博客网 时间:2024/05/18 01:10

时间:2013.12.27

地点:软件大楼211

----------------------------------------------------------------------------------------------————

一、简述

  二叉查找(Binary search)算法在数组有序时时间复杂度为O(log n),一种合理的设计方式是函数原型包活6个参数,头三个参数为数组自身、查找起始下标、查找范围元素个数,后面3个参数为查找目标、查找成功与否标志、索引。

函数原型可声明如下:

void binary_search(const int a[], size_t first, size_t size, int target, bool &found, size_t &location);//前置条件:从a[first]开始、含有size个元素的数组段,其元素从下到大排列//后置条件:从a[first]开始,含有size个元素的数组段中查找target。如果找到target//          那么found为true,并设置location,使得target==a[location],否则found//          设置为false

二、实现

  二叉树的算法思想和简单,无非是对查找区域不断递归搜索目标,期间我们不断折半缩小查找范围,当范围数组个数为0时停止递归。但在递归调用时,由于范围不断的变化,因此下标的计算很容易出错。因此总结如下,在其他类似折半处理过程中经常用到:

1.计算数组中间元素索引公式为:        middle=first+size/2;

2.中间元素除外的前半段元素个数为: size/2;

2.中间元素除外的后半段元素个数为: (size-1)/2;     //数学上应为(size/2)-1,但如此当size=1时会导致索引为负操作,我们做恰当的处理,如此计算后的索引不可能出现为负的情况。

三、代码

  下面为二叉查找函数的一个实现

void binary_search(const int a[], size_t first, size_t size, int target, bool &found, size_t &location)//前置条件:从a[first]开始、含有size个元素的数组段,其元素从下到大排列//后置条件:从a[first]开始,含有size个元素的数组段中查找target。如果找到target//          那么found为true,并设置location,使得target==a[location],否则found//          设置为false{size_t middle;if (size == 0)found = false;else{middle = first + size / 2;if (target == a[middle]){location = middle;found = true;}else if (target < a[middle]){binary_search(a, first, size / 2, target, found, location);}else{binary_search(a, middle + 1, (size-1 )/ 2, target, found, location);}}}


0 0
原创粉丝点击