Category >
CSHARP
|| Published on :
Tuesday, March 14, 2023 || Views:
344
||
C# array searching linear search binary search algorithms efficiency
This article explores the basics of searching in C# arrays, with a focus on the linear and binary search algorithms. It provides example codes for both search methods and explains the differences between them. By the end of this article, readers will have a better understanding of how to efficiently search arrays in C#.
Searching is a common operation performed on arrays in C#. Arrays are a collection of items of the same data type stored in contiguous memory locations. In this article, we'll explore how to search for elements in a C# array.
Linear Search in C#
Linear search is a simple search algorithm that scans the array sequentially and compares each element with the search key until a match is found. If the key is found, the index of the element is returned. Otherwise, the function returns -1 to indicate that the key is not present in the array.
Here is an example of linear search in C#:
int[] array = { 3, 5, 2, 8, 1, 9, 4 };
int key = 8;
int index = -1;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == key)
{
index = i;
break;
}
}
if (index != -1)
{
Console.WriteLine("Element found at index " + index);
}
else
{
Console.WriteLine("Element not found");
}
Binary Search in C#
Binary search is a more efficient search algorithm that works on a sorted array. It repeatedly divides the search interval in half until the key is found or the interval is empty.
The Array.BinarySearch() method in C# can be used to perform binary search on an array. Here is an example:
int[] array = { 1, 2, 3, 4, 5, 8, 9 };
int key = 5;
int index = Array.BinarySearch(array, key);
if (index >= 0)
{
Console.WriteLine("Element found at index " + index);
}
else
{
Console.WriteLine("Element not found");
}
Note that the Array.BinarySearch() method returns the index of the key if it is found in the array. If the key is not found, it returns a negative number that is the bitwise complement of the index of the first element that is larger than the key, or the length of the array if all elements are smaller than the key.
Conclusion
Searching for elements in an array is a fundamental operation in C#. Linear search is a simple algorithm that works on unsorted arrays, while binary search is a more efficient algorithm that works on sorted arrays. By using the built-in Array.BinarySearch() method in C#, you can perform binary search on an array with ease.