C# - Searching Algorithms(Linear Search, Binary Search)
Searching algorithms are used to find the position or presence of a specific element in a collection of data. Here are two commonly used searching algorithms: Linear Search and Binary Search.
Linear Search:
Linear search is a simple searching algorithm that checks each element in the collection one by one until the target element is found or the entire collection is exhausted. It is applicable to both sorted and unsorted collections.
Algorithm Steps:
-
Start from the first element of the collection.
- Compare the current element with the target element.
- If the current element matches the target element, return the index of the current element.
- If the target element is not found, move to the next element and repeat steps 2 and 3 until the end of the collection is reached.
Linear search has a time complexity of O(n) because, in the worst case, it may have to check all n elements in the collection.
C# Implementation of Linear Search:
public static int LinearSearch(int[] arr, int target)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == target)
return i; // Target found, return its index
}
return -1; // Target not found
}
Binary Search:
Binary search is an efficient searching algorithm applicable only to sorted collections. It repeatedly divides the search space in half, eliminating the half that cannot contain the target element.
Algorithm Steps:
-
Compare the target element with the middle element of the sorted collection.
- If the middle element is the target element, return its index.
- If the target element is less than the middle element, search in the left half of the collection; otherwise, search in the right half.
- Repeat steps 1-3 with the appropriate half of the collection until the target element is found, or the search space is empty.
Binary search has a time complexity of O(log n) because, in each step, the search space is reduced by half.
C# Implementation of Binary Search:
public static int BinarySearch(int[] arr, int target)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid; // Target found, return its index
else if (arr[mid] < target)
left = mid + 1; // Search in the right half
else
right = mid - 1; // Search in the left half
}
return -1; // Target not found
}
Binary search is much faster than linear search for large sorted collections, but it requires the collection to be sorted before performing the search. If the collection is unsorted or changes frequently, linear search might be a more suitable choice.