C++でのペアのソートされたベクトルでの二分探索
これは、ソートされたペアのベクトルでバイナリ検索を実装するためのC++プログラムです。
アルゴリズム
Begin Declare a structure keycompare. Function operator()(const pair& v, const int& k) returns Booleans. Status = v.first < k. Return status. Function operator()(const pair& v, const int& k) returns Booleans. Status = k < v.first. Return status. Declare a vector v. Declare key and value pair within v of the integer datatype. Call push_back() function to insert values in v vector. Call sort() function to sort all elements of the vector v. Print “Sorted vector”. Print “Key” “Value”. for (pair& n : v) print the first and second value of n. if (binary_search(v.begin(), v.end(), 50,keycompare())) then print “50 exists in vector”. Else Print “50 does not exist”. if (binary_search(v.begin(), v.end(), 7,keycompare() )) then print “7 exists in vector”. Else Print “7 does not exist”. End.
サンプルコード
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct keycompare {
bool operator()(const pair<int, int>& v, const int& k) {
return (v.first < k);
}
bool operator()(const int& k, const pair<int, int>& v) {
return (k < v.first);
}
};
int main() {
vector<pair<int, int>> v;
v.push_back(make_pair(7, 26));
v.push_back(make_pair(6, 76));
v.push_back(make_pair(4, 16));
v.push_back(make_pair(5, 36));
sort(v.begin(), v.end());
cout<<"Sorted vector"<<endl;
cout << "KEY" << '\t' << "VALUE" << endl;
for (pair& n : v)
cout << n.first << '\t' << n.second << endl;
if (binary_search(v.begin(), v.end(), 50,keycompare()))
cout << "50 exists in vector";
else
cout << "50 does not exist";
cout << endl;
if (binary_search(v.begin(), v.end(), 7,keycompare() ))
cout << "7 exists in vector";
else
cout << "7 does not exist";
return 0;
} 出力
Sorted vector KEY VALUE 4 16 5 36 6 76 7 26 50 does not exist 7 exists in vector
-
C++での二分木から二分探索木への変換
二分木 は、ツリーの各ノードが最大2つの子ノードを持つことができる特殊なタイプのツリーです。これらの子ノードは、右の子および左の子と呼ばれます。 単純な二分木は-です 二分探索木(BST) は、次のルールに従う特殊なタイプのツリーです- 左の子ノードの値は常に親よりも小さくなります注 右側の子ノードは、親ノードよりも大きな値を持っています。 すべてのノードが個別に二分探索木を形成します。 二分探索木(BST)の例 − バイナリ検索ツリーは、検索、最小値と最大値の検索などの操作の複雑さを軽減するために作成されます。 ここでは、二分木が与えられており、
-
C ++プログラムでの二分探索?
二分探索は、半区間探索、対数探索、または二分探索とも呼ばれ、ソートされた配列内のターゲット値の位置を見つける検索アルゴリズムです。二分探索は、ターゲット値を配列の中央の要素と比較します。それらが等しくない場合、ターゲットが存在できない半分が削除され、残りの半分で検索が続行され、再び中央の要素がターゲット値と比較され、ターゲット値が見つかるまでこれが繰り返されます。残りの半分が空の状態で検索が終了した場合、ターゲットは配列に含まれていません。アイデアは単純ですが、バイナリ検索を正しく実装するには、特に配列の値が範囲内の整数のすべてではない場合、終了条件と中間点の計算に関する微妙な点に注意する必要