DEV Community

Niels Swimburger.NET ๐

Posted on • Originally published at swimburger.net on

Generic Linear Search/Sequential Search for a sequence in C# .NET

Early this year, I decided to brush up on my algorithms and data structure knowledge. I took these great two courses (1, 2) on PluralSight by Robert Horvick.

To practice what I learned in this course, I decided to create generic versions of the different algorithms and data structures.

What do I mean by generic versions? These types of courses always use integers or strings to demonstrate the algorithms. Instead of using those primitive data types, I'm reimplementing the algorithms and data structures using C#'s generic type parameters.

Here's a console application with a generic method `LinearSearchSequence` to perform a linear search looking not for just one T, but a sequence of T:

``````using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
var numbers = Enumerable.Range(250, 750).ToArray();

var index = LinearSearchSequence(numbers, new int[] { 500, 501, 502 });
Console.WriteLine("Linear Search Sequence:");
Console.WriteLine(index);
}

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;
}
}
``````

By using a generic type parameter with the constraint that the type has to implement the `IComparable` interface, you can perform the linear search algorithm without knowing the exact type you are working with.

If you want to understand the logic behind the quick sort algorithm, I recommend checking out the courses mentioned earlier. There's also a lot of other great resources out there online!

Disclaimer: This code works, but is only developed for the sake of practice. Use at your own risk or just use a sorting library. If you see some room for improvement, there most likely is, I'm all ears~