2.3-5 Binary Search

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

<< Introduction to algorithms >> ( Second Edition )

Exercise 2.3-5

Referring back to the searching problem ( see Exercise 2.1-3 ), observe that if the

sequence A is sorted, we can check the midpoint of the squence against v and

eliminate half of the sequence from further consideration. Binary search is an

algorithm that repeats this procedure, halving the size of remaining portion of

the sequence each time. Write pseudocode, either iterative or recursive, for binary

search. Argue that the worst-case running time of binary search is O( nlgn )

Solution:

// 声明:本代码旨在实现原文的思想

// copyleft 2004 http://blog.csdn.net/mskia

// email: bitrain@hotmail.com

#ifndef Binary_Search_by_mskia

#define Binary_Search_by_mskia

namespace te {

template< class T >

T *binary_search( const T &target , T *first , T *last ) {

while ( first <= last ) {

T *mid = first + ( ( last - first ) >> 1 );

if ( *mid == target ) {

return mid;

} else if ( target < *mid ) {

last = mid - 1;

} else {

first = mid + 1;

}

}

return NULL;

}

}

#endif

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航