private static void SearchViaFunc() { var generator = new Random(); var data = new int[10]; for (var i = 0; i < data.Length; i++) { data[i] = generator.Next(10, 100); } Console.WriteLine(string.Join(" ", data) + NewLine); Console.Write("Enter an integer value (-1 to quit): "); var searchInt = int.Parse(Console.ReadLine()); while (searchInt != -1) { var position = Searching.LinearSearch(data, searchInt, (v1, v2) => v1.CompareTo(v2) == 0); Console.WriteLine(position != -1 ? $"The integer {searchInt} was found in position {position}.{NewLine}" : $"The integer {searchInt} was not found.{NewLine}"); Console.Write("Enter an integer value (-1 to quit): "); searchInt = int.Parse(Console.ReadLine()); } }
static void Main(string[] args) { #region Linear Searching List <int> sortedData = FileHandler.ReadSortedFile(); Console.WriteLine("---Linear Search---"); DateTime startTime = DateTime.Now; Searching.LinearSearch(sortedData, 1500); TimeSpan time = DateTime.Now - startTime; Console.WriteLine("-------------------"); Console.WriteLine("Total Time: {0}.{1}", time.Seconds, time.Milliseconds); Console.WriteLine("-------------------"); Console.WriteLine(); Console.ReadKey(); #endregion #region Binary Searching List <int> sortedData2 = FileHandler.ReadSortedFile(); int count = sortedData.Count - 1; Console.WriteLine("---Binary Search---"); DateTime startTime2 = DateTime.Now; while (count > -1) { Searching.BinarySearch(sortedData2, count); count -= 1500; } TimeSpan time2 = DateTime.Now - startTime2; Console.WriteLine("-------------------"); Console.WriteLine("Total Time: {0}.{1}", time2.Seconds, time2.Milliseconds); Console.WriteLine("-------------------"); Console.ReadKey(); #endregion }
private static void LinearSearchElementAndPrintIndex(int[] arr, int elementToSearch) { int position = Searching.LinearSearch(arr, elementToSearch); string result = (position == -1) ? $"Element {elementToSearch} is not present in the given array" : $"Element {elementToSearch} is present at index {position}"; Console.WriteLine(result); }
public void GivenATarget_WhenArraysContains_ShouldReturnTheIndexOfTheTarget() { // Arrange var array = new int[] { 1, 2, 3 }; var target = 2; // Act var index = Searching.LinearSearch(array, target); // Assert index.Should().Be(1); }
public void GivenATarget_WhenArrayNotContains_ShouldReturnNegativeOne() { // Arrange var array = new int[] { 1, 2, 3 }; var target = 4; // Act var index = Searching.LinearSearch(array, target); // Assert index.Should().Be(-1); }