Yurttas/PL/OOL/Cplusplus/F/02/04/04/01/binary search int.cpp

 1/*
 2   Copyright(C) 1998
 3   All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
 4
 5   Permission to use, copy, modify, and distribute this
 6   software and its documentation for EDUCATIONAL purposes
 7   and without fee is hereby granted provided that this
 8   copyright notice appears in all copies.
 9  
10   date   : January 1, 1998.
11   authorĀ : Salih Yurttas.
12
13   binary_search_int.cpp
14*/
15
16
17#include <vector>
18
19using namespace std;
20
21bool binary_search_int(int key,
22                       vector<int>& list) {
23  bool found = false;
24
25  int low = 0;
26  int high = list.size();
27
28  int mid;
29
30  while(low<=high&&!found) {
31    mid = low+(high-low)/2;
32    if(key==list[mid])
33      found = true;         /* found it!             */
34    else if(key<list[mid])
35      high = mid-1;         /* search the lower part */
36    else               
37      low = mid+1;          /* search the upper part */
38  }
39  return found;
40}