Created
January 28, 2021 23:18
-
-
Save Swimburger/d2c5d138591cef01b1bf4a5ed596a69e to your computer and use it in GitHub Desktop.
Generic Linear Sequence Search in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var numbers = Enumerable.Range(0, 1000).ToArray(); | |
var index = LinearSearchSequence(numbers.AsEnumerable(), new int[] { 500, 501, 502 }); | |
Console.WriteLine("Linear Search Sequence:"); | |
Console.WriteLine(index); | |
Console.ReadKey(); | |
Console.Clear(); | |
} | |
private static int LinearSearchSequence<T>(IEnumerable<T> list, IEnumerable<T> needle) where T : IComparable | |
{ | |
var needleArray = needle.ToArray(); | |
var needleLength = needleArray.Length; | |
var listLength = list.Count(); | |
for (int i = 0; i <= listLength - needleLength; i++) | |
{ | |
for (int matchIndex = 0; matchIndex < needleLength; matchIndex++) | |
{ | |
var item = list.ElementAt(i + matchIndex); | |
var needleItem = needleArray[matchIndex]; | |
if (item.CompareTo(needleItem) != 0) | |
{ | |
break; | |
} | |
if (matchIndex == needleLength - 1) | |
{ | |
return i; | |
} | |
} | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment