Search
Last updated
Last updated
The simplest form of search, just linearly walking through a DS and checking if the value in the current position is the desired value.
This will be , since in the worst case your desired value will be at the last position, or is not found.
You keep halving your DS input and checking if the value is greater or smaller than your desired value.
It is required that the DS is sorted.
This will be , since you don't scan the sections. You only find the half position, check it's value and try to half again until the section lenght if 1.
Is a Graph or Tree traversal algorithm used to explore nodes and edges. It can also be used as a Search algorithm.
It is widely used in numerous situations such as shortest-path calculations, network analysis, and more.
It doesn't preserve shape of the traversal.
It uses Queue
to store nodes in order.
Each node is visited once, and all its edges are traversed once.
BFS explores all nodes at the current "depth" (or level) before moving to nodes at the next depth.
In Graphs, you must also mark visited nodes, so that they don't get pushed again to the Queue
.
In BST
where you garantee order, you may add additional conditions to prioritize going left or right first, depending on the needle
value.
At start node N
:
Push N
to the Queue
.
Push N's
children to the Queue
.
Process N
and remove it from the Queue
.
Go to next node N
at Queue
:
Push its children to the Queue
.
Process node N
, and remove it from Queue
.
Repeat 2.
until all nodes were processed.
Is a Graph or Tree traversal algorithm used to explore nodes and edges. It can also be used as a Search algorithm.
Preserves the shape of the traversal.
It uses Stack
to store nodes in order.
DFS explores entire branches (goes all the way to the leafs) first before moving to neighbor branches.
In Graphs, you must also mark visited nodes, so that they don't get pushed again to the Stack
.
In BST
where you garantee order, you may add additional conditions to prioritize going left or right first, depending on the needle
value.
At start node N
:
Push N
to the Stack
.
Push N's
children to the Stack
.
Process N
and remove it from the Stack
.
Pop next node N
(last) from Stack
:
Push its children to the Stack
.
Process node N
, and remove it from Stack
.
Repeat 2.
until all nodes were processed.
For a Graph with V
vertices and E
edges, .
For a Tree with N
nodes, .