From 68602a68d8b7a0eb820f2fcfdd16efa1149bfeed Mon Sep 17 00:00:00 2001 From: rosskyl Date: Wed, 31 Oct 2018 09:35:22 -0500 Subject: [PATCH] Linear search in CSharp --- CSharpLinearSearch/LinearSearch.cs | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 CSharpLinearSearch/LinearSearch.cs diff --git a/CSharpLinearSearch/LinearSearch.cs b/CSharpLinearSearch/LinearSearch.cs new file mode 100644 index 0000000..ea6e879 --- /dev/null +++ b/CSharpLinearSearch/LinearSearch.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; + +namespace ConsoleApp1 +{ + class Program + { + static void Main(string[] args) + { + List myList = new List() { 3, 9, 1, 2, 5, 100, 2123, 54, 34, 123, 534 }; + Console.Write("List = "); + PrintList(myList); + int index = LinearSearch(myList, 1); + Console.WriteLine("1 found at " + index); + index = LinearSearch(myList, 4); + Console.WriteLine("4 found at " + index); + Console.WriteLine("Press enter when done"); + Console.ReadLine(); + } + public static int LinearSearch(List list, int target) + { + for (int i = 0; i < list.Count; i++) + { + if (list[i] == target) + { + return i; + } + } + return -1; + } + public static void PrintList(List list) + { + foreach (int item in list) + { + Console.Write(item + " "); + } + Console.WriteLine(); + } + } +}