Short Note On binary search and binary tree
Binary search is a searching algorithm used to find the position of a target value within a sorted array. Here's how it works:
- Start by setting the lower bound low to 0 and the upper bound high to the length of the array minus 1.
- Calculate the middle index mid as the average of low and high, rounded down to the nearest integer.
- Compare the target value with the value at the middle index in the array:
- If they're equal, the target value has been found. Return the middle index.
- If the target value is less than the middle value, set high to mid - 1 and repeat step 2.
- If the target value is greater than the middle value, set low to mid + 1 and repeat step 2.
- If the target value is not found after iterating through the array, return -1 to indicate that the value was not found.
Here's the pseudocode for this algorithm:
function binarySearch(array, target):
low = 0
high = array.length - 1
while low <= high:
mid = floor((low + high) / 2)
if array[mid] == target:
return mid
else if array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Note that this algorithm assumes that the array is sorted in ascending order. If the array is sorted in descending order, you'll need to adjust the comparison logic accordingly. Additionally, if there are duplicate values in the array, the algorithm may return any index that contains the target value.
A binary tree is a tree-like data structure where each node can have at most two children, referred to as the left child and the right child. The topmost node of the tree is called the root, and the nodes with no children are called leaves. Here's an example of a binary tree:
1
/ \
2 3
/ \ / \
4 5 6 7
In this example, the root node has two children: the left child is node 2 and the right child is node 3. Node 2 has two children: the left child is node 4 and the right child is node 5. Nodes 4, 5, 6, and 7 are all leaves.
Binary trees can be useful for organizing and searching data. Some common operations on binary trees include inserting and deleting nodes, searching for a value, and traversing the tree to visit each node. There are three main types of binary tree traversals:
In-order traversal: Visit the left subtree, then the root, then the right subtree.
Pre-order traversal: Visit the root, then the left subtree, then the right subtree.
Post-order traversal: Visit the left subtree, then the right subtree, then the root.
These traversals can be performed recursively or iteratively using a stack. Binary trees can also be used to implement binary search trees, which provide efficient searching and sorting operations by maintaining a certain order among the nodes.
Comments
Post a Comment