检索之二分检索

上代码:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4  
 5 class Item
 6 {
 7 private:
 8     int Key;
 9 public:
10     Item(int value):Key(value){}
11     int getKey()
12     {
13        return Key;
14     }
15     void setKey(const int &K)
16     {
17        this->Key = K;
18     }
19 };
20  
21 int BinSearch(vector<Item *> &dataList, int length, const int &K)
22 {
23   int low = 0 ;
24   int high = length;
25   int mid;
26   while(low <= high)
27   {
28     mid = (low + high)/2;
29     if(K < dataList[mid]->getKey())
30     {
31       high = mid -1;
32     }
33     else if(K > dataList[mid]->getKey())
34     {
35       low = mid +1;
36     }
37     else
38     {
39       return mid;
40     }
41  }
42     return 0;
43  }
44  
45 int main()
46 {
47   vector<Item *> datalist;
48   int key;
49   int fn;
50   int ifn;
51   cout<<"input the key : "<< endl;
52   cin>> key;
53   while(key >= 0)
54   {
55       datalist.push_back(new Item(key));  
56       cin>> key;
57   }
58   int len = datalist.size();
59   cout<< "The datalist size is :" <<endl;
60   cout<< len << endl;
61   cout<< "input the key value to be found : "<<endl;
62   cin>> ifn;
63   fn=BinSearch(datalist, len, ifn);
64   cout<< "The position index is : " << endl;
65   cout<<fn<<endl;
66   for(vector<Item *>::iterator it= datalist.begin(); it!=datalist.end(); it++)
67       delete *it;
68  
69      
70   return 0;
71  }

Fight fight fight ! 你有你的奇迹 ! Fight fight fight ! Just to be yourself !
原文地址:https://www.cnblogs.com/sjlove/p/3106820.html