Searching

Searching in data structures is the process of locating a specific element (or target value) within a collection of data. It's a fundamental operation crucial for various tasks like retrieval, analysis, and manipulation of data.

Here are common types of searching algorithms:

  1. Linear Search:

    • Simplest approach: Checks each element sequentially until the target is found or the end is reached.

    • Time complexity: O(n) in the worst and average cases, O(1) in the best case (if the target is at the beginning).

    • Unsuitable for large datasets due to its linear time complexity.

  2. Binary Search:

    • Efficient algorithm for sorted arrays: Repeatedly divides the search interval in half until the target is found or the interval is empty. Requires a sorted array.

    • Time complexity: O(log n) in the worst, average, and best cases.

    • Significantly faster than linear search for large datasets.

  3. Binary Search Tree:

    • Creates a binary search tree (BST) from the input data.

    • Performs an in-order traversal of the BST to retrieve elements in sorted order.

    • Time complexity: O(n log n) average case, O(n^2) worst case (skewed trees).

  4. Graph Traversal:

    • Uses algorithms like depth-first search (DFS), breadth-first search (BFS) or Kahn's algorithm. The BFS used to find closest elements where else DFS to check if element or path exists.

    • Algorithms like Dijkstra's and Bellman-Ford involve sorting edges or vertices based on their distances or weights.

Factors to consider when choosing a search algorithm:

  • Data structure: The type of data structure used to store the elements (e.g., array, list, tree).

  • Order of elements: Whether the elements are sorted or unsorted.

  • Size of the dataset: The number of elements to be searched.

  • Frequency of searches: How often searches are performed.

  • Time complexity: How long the algorithm takes to run in terms of input size.

  • Space complexity: How much extra memory the algorithm requires.

Examples

Complexity

  • Time complexity: O(log N)

  • Space complexity: O(1)

Complexity

  • Time complexity: O(V) , where V is the number of nodes.

  • Space complexity: O(V) , where V is the number of nodes.

Complexity

  • Time complexity: O(V+E),where V is the number of vertices and E is the number of edges.

  • Space complexity: O(V) for the visited array and queue.

Complexity

  • Time complexity: O(V) , where V is the number of nodes.

  • Space complexity: O(V) , where V is the number of nodes.

Complexity

  • Time complexity: O(V+E),where V is the number of vertices and E is the number of edges.

  • Space complexity: O(V) for the visited array and stack.

Last updated