Writing a linear search algorithm in C#
The linear search algorithm is a basic search algorithm that starts from the beginning of an array and visits each value until it matches the value that’s being searched. In the previous algorithm, selection sort, a linear search already takes place where values are compared with the less than (<
) comparison operator to find the lowest value. The basic version of linear search only needs one loop and will use the equality operator (==
) to find the value. If the loop reaches the end of the array, then the value does not exist within the array. Let’s build a short example of linear search within an array:
int[] testArray = {13, 55, 0, -4, 80, 7, 20}; int searchValue = 0; for (int index = 0; index < testArray.Length; index++) { if(searchValue == testArray[index]) { Console.WriteLine("Value found!"); ...