What Is Searching With Example in Data Structure?

//

Scott Campbell

What Is Searching With Example in Data Structure?

Searching is one of the fundamental operations in data structures that allows us to find a specific element within a collection of data. It involves examining each element in a structured manner until the desired element is found. In this article, we will explore various searching techniques and provide examples to illustrate their usage.

Linear Search

The linear search algorithm is the simplest and most straightforward method for searching an element in an array or list. It sequentially checks each element until a match is found or the entire collection has been traversed.

Algorithm:

  1. Start from the first element of the array.
  2. Compare the current element with the Target element.
  3. If they match, return the index of the current element.
  4. If not, move to the next element and repeat steps 2 and 3.
  5. If the end of the array is reached without finding a match, return -1 to indicate that the Target element is not present.

Example:

Consider an array: [4, 9, 2, 7, 5]

Let’s search for the Target element “7” using linear search:

Step 1: Start from index 0 -> Element at index 0: 4. No match.

Step 2: Move to index 1 -> Element at index 1: 9.

Step 3: Move to index 2 -> Element at index 2: 2.

Step 4: Move to index 3 -> Element at index 3: 7. Match found!

The Target element “7” is present at index 3 in the array.

Binary Search

Binary search is an efficient searching technique that requires the data to be sorted in ascending or descending order. It works by repeatedly dividing the search space in half until the Target element is found.

Algorithm:

  1. Consider the middle element of the sorted array.
  2. If it matches the Target element, return its index.
  3. If it is greater than the Target element, repeat the process on the left half of the array.
  4. If it is less than the Target element, repeat the process on the right half of the array.
  5. Continue dividing and searching until a match is found or there are no more elements to search.

Consider a sorted array: [2, 4, 5, 7, 9]

Let’s search for the Target element “5” using binary search:

Step 1: Consider middle index -> Element at index (0 + (4-0) / 2) = 5. Match found!

The Target element “5” is present at index 2 in the array.

In conclusion, searching algorithms play a crucial role in data structures as they allow us to efficiently locate specific elements within collections. Both linear and binary search techniques provide different approaches depending on whether data is sorted or not. By understanding and utilizing these algorithms effectively, we can optimize our code for optimum performance when working with large datasets.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy