Search Algorithms
In the context of data structures and algorithms, search algorithms are used to find a specific element in a collection of data. They are essential for efficiently searching through large data sets and solving various problems.
One commonly used search algorithm is binary search. Binary search is an efficient algorithm for finding an element in a sorted array. It works by repeatedly dividing the search space in half until the target element is found or determined to be not present.
Here's an example of binary search implemented in C++:
TEXT/X-C++SRC
1{{ code }}
xxxxxxxxxx
35
}
using namespace std;
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 7, 10, 14, 23, 34, 45};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1) {
cout << "Element not found";
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment