Home > Article > Backend Development > How to implement linear search algorithm in C#
How to implement the linear search algorithm in C
#Preface:
Linear search is one of the simplest and most basic search algorithms in computer science. It is a sequential search method that determines whether the target element exists by comparing the elements in the list one by one. This article will introduce how to implement the linear search algorithm in C# and provide specific code examples.
using System; public class LinearSearch { public static int Find(int[] arr, int target) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == target) { return i; } } return -1; } } public class Program { public static void Main(string[] args) { int[] arr = { 2, 4, 6, 8, 10 }; int target = 6; int result = LinearSearch.Find(arr, target); if (result == -1) { Console.WriteLine("目标元素不存在!"); } else { Console.WriteLine("目标元素的索引是:" + result); } } }
In the above code, we first define a file namedLinearSearch
class, the Find
method accepts an integer array and the target integer as parameters, and returns the index of the target integer in the array. In the Find
method, we use a for
loop to traverse the list and compare the elements one by one to see if they are equal to the target element. If there are equal elements, return the index of the element; if there is no equality element, then -1 is returned to indicate that the target element does not exist.
In the Main
method, we create an integer array arr
and a target integer target
, and call LinearSearch.Find
Method to find the index of the target integer in the array. Based on the search results, we print out the corresponding information.
I hope this article will help you understand and implement the linear search algorithm in C#!
The above is the detailed content of How to implement linear search algorithm in C#. For more information, please follow other related articles on the PHP Chinese website!