Mass++ Common Libraries v2.7.5
 All Classes Namespaces Files Functions Variables Enumerations Macros
SearchTool.h
Go to the documentation of this file.
1 
12 #ifndef __KOME_CORE_SEARCH_TOOL_H__
13 #define __KOME_CORE_SEARCH_TOOL_H__
14 
15 
16 #include <boost/function.hpp>
17 
18 
19 namespace kome {
20  namespace core {
21 
26  class CORE_TOOLKITS_CLASS SearchTool {
27  public:
47  template< typename S, typename T >
48  static int binarySearch(
49  S value,
50  boost::function< T ( int ) > getElementFun,
51  boost::function< int ( T, S ) > compareFun,
52  int size
53  ) {
54  // range of search
55  int top = 0;
56  int bottom = size - 1;
57  int idx = -1;
58 
59  // search
60  while( top <= bottom && idx < 0 ) {
61  // get element located middle of searching range
62  int mid = ( top + bottom ) / 2;
63  T elm0 = getElementFun( mid );
64 
65  // compare
66  int cmp = compareFun( elm0, value );
67  if( cmp == 0 ) { // particular element is found.
68  idx = mid;
69 
70  // return the first of particular elements.
71  mid--;
72  while( mid >= top ) {
73  T elm1 = getElementFun( mid );
74  if( compareFun( elm1, value ) == 0 ) { // particular element
75  idx = mid;
76  mid--;
77  }
78  else {
79  mid = top - 1;
80  }
81  }
82  }
83  else if( cmp > 0 ) { // Element's value is greater than searching value.
84  bottom = mid - 1;
85  }
86  else { // Element's value is less than searching value.
87  top = mid + 1;
88  }
89  }
90 
91  if( idx < 0 ) { // not found
92  idx = - top - 1;
93  }
94 
95  return idx;
96  }
97  };
98  }
99 }
100 
101 #endif // __KOME_CORE_SEARCH_TOOL_H__
static int binarySearch(S value, boost::function< T(int) > getElementFun, boost::function< int(T, S) > compareFun, int size)
binary search
Definition: SearchTool.h:48
This class has some searching algorithm method.
Definition: SearchTool.h:26