Searching is needed when we have a large array of some data or objects & need to find the position of a particular element. We may also need to check if an element exists in a list or not. While there are built in functions that offer these capabilities, they only work with predefined datatypes. Therefore there may the need for a custom function that searches elements & finds the position of elements. Below you will find two search techniques viz. Linear Search & Binary Search implemented in C#. The code is simple & easy to understand & can be modified as per need.
Linear Search Technique in C Sharp
using System; using System.Text; using System.Threading.Tasks; namespace Linear_Search { class Program { static void Main(string[] args) { Int16[] array = new Int16[100]; Int16 search, c, number; Console.WriteLine("Enter the number of elements in array\n"); number = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter " + number.ToString() + " numbers\n"); for (c = 0; c < number; c++) { array[c] = new Int16(); array[c] = Convert.ToInt16(Console.ReadLine()); } Console.WriteLine("Enter the number to search\n"); search = Convert.ToInt16(Console.ReadLine()); for (c = 0; c < number; c++) { if (array[c] == search) /* if required element found */ { Console.WriteLine("" + search.ToString() + " is present at location " + (c + 1).ToString() + ".\n"); break; } } if (c == number) Console.WriteLine(search.ToString() + " is not present in array.\n"); Console.ReadLine(); } } } |
Binary Search Technique in C Sharp
using System; using System.Text; using System.Threading.Tasks; namespace Binary_Search { class Program { static void Main(string[] args) { int c, first, last, middle, n, search; Int16[] array = new Int16[100]; Console.WriteLine("Enter number of elements\n"); n = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter " + n.ToString() + " integers\n"); for (c = 0; c < n; c++) { array[c] = new Int16(); array[c] = Convert.ToInt16(Console.ReadLine()); } Console.WriteLine("Enter value to find\n"); search = Convert.ToInt16(Console.ReadLine()); first = 0; last = n - 1; middle = (first + last) / 2; while (first <= last) { if (array[middle] < search) first = middle + 1; else if (array[middle] == search) { Console.WriteLine(search + " found at location " + (middle + 1)); break; } else last = middle - 1; middle = (first + last) / 2; } if (first > last) Console.WriteLine("Not found! " + search + " is not present in the list."); Console.ReadKey(); } } } |