The binary search algorithm and the binary search tree (BST) are two distinct concepts that, while related, serve different purposes in computer science.
The binary search algorithm is a searching technique used on sorted arrays or containers. It operates by repeatedly dividing the search interval in half.
If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half.
Otherwise, it narrows it to the upper half. This process continues until the search key is found or the interval is empty.
Key Characteristics:
The following program uses the standard library’s binary search algorithm:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> Numbers{1, 2, 3, 4, 5};
int target = 4;
bool found = std::binary_search(
Numbers.begin(), Numbers.end(), target);
std::cout << "The number " << target
<< (found ? " was" : " was not") << " found";
}
The number 4 was found
A binary search tree is a data structure that facilitates fast lookup, addition, and removal of items. Each node in the BST has up to two children, referred to as the left child and the right child.
For any node, the left subtree contains values less than the node's value, and the right subtree contains values greater than the node's value.
Key Characteristics:
The following program creates a binary search tree from scratch:
#include <iostream>
struct Node {
int data;
Node* left;
Node* right;
};
Node* newNode(int data) {
Node* node = new Node();
node->data = data;
node->left = nullptr;
node->right = nullptr;
return node;
}
Node* insert(Node* root, int data) {
if (root == nullptr) {
return newNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
bool search(Node* root, int data) {
if (root == nullptr) {
return false;
}
if (root->data == data) {
return true;
}
if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
int main() {
Node* root = nullptr;
root = insert(root, 4);
insert(root, 2);
insert(root, 5);
insert(root, 1);
insert(root, 3);
int target = 4;
bool found = search(root, target);
std::cout << "The number " << target
<< (found ? " was" : " was not") << " found";
}
The number 4 was found
Understanding both concepts is crucial for efficient searching and data management in various applications.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the advantages of binary search, and how to use it with the C++ standard library algorithms binary_search()
, lower_bound()
, upper_bound()
, and equal_range()