Skip to content

Instantly share code, notes, and snippets.

@Swimburger
Created January 28, 2021 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swimburger/d2c5d138591cef01b1bf4a5ed596a69e to your computer and use it in GitHub Desktop.
Save Swimburger/d2c5d138591cef01b1bf4a5ed596a69e to your computer and use it in GitHub Desktop.
Generic Linear Sequence Search in C#
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