CSharp examples for Data Structure Algorithm:Search
binary search to find an integer on an array
using System;//from w ww. j a v a2 s . c o m public class MainClass { static void Main() { var generator = new Random(); var data = new int[15]; // fill array with random ints in range 10-99 for (var i = 0; i < data.Length; ++i) { data[i] = generator.Next(10, 100); } Array.Sort(data); // elements must be sorted in ascending order DisplayElements(data, 0, data.Length - 1); // display array Console.Write("\nPlease enter an integer value (-1 to quit): "); int searchInt = int.Parse(Console.ReadLine()); // repeatedly input an integer; -1 terminates the app while (searchInt != -1) { // perform binary search int position = BinarySearch(data, searchInt); if (position != -1) // integer was found { Console.WriteLine($"The integer {searchInt} was found in " + $"position {position}.\n"); } else // integer was not found { Console.WriteLine($"The integer {searchInt} was not found.\n"); } Console.Write("Please enter an integer value (-1 to quit): "); searchInt = int.Parse(Console.ReadLine()); } } public static int BinarySearch(int[] values, int searchElement) { var low = 0; // low end of the search area var high = values.Length - 1; // high end of the search area var middle = (low + high + 1) / 2; // middle element do { // display remaining elements of array DisplayElements(values, low, high); // indicate current middle; pad left with spaces for alignment Console.WriteLine("-- ".PadLeft((middle + 1) * 3)); // if the element is found at the middle if (searchElement == values[middle]) { return middle; // search key found, so return its index } // middle element is too high else if (searchElement < values[middle]) { high = middle - 1; // eliminate the higher half } else // middle element is too low { low = middle + 1; // eliminate the lower half } middle = (low + high + 1) / 2; // recalculate the middle } while (low <= high); return -1; // search key was not found } public static void DisplayElements(int[] values, int low, int high) { Console.Write(string.Empty.PadLeft(low * 3)); for (var i = low; i <= high; ++i) { Console.Write($"{values[i]} "); } } }