**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:**

- Start from the first element of the array.
- Compare the current element with the Target element.
- If they match, return the index of the current element.
- If not, move to the next element and repeat steps 2 and 3.
- 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:**

- Consider the middle element of the sorted array.
- If it matches the Target element, return its index.
- If it is greater than the Target element, repeat the process on the left half of the array.
- If it is less than the Target element, repeat the process on the right half of the array.
- 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.