Linear Search .Net

Searches particular value within a data structure. Linear search checks each element in the list until a match is found or until it reaches the end. Linear Search Function

Consider the linear function as “LinearSearch(arr,value)”

1. where arr is the array to search inside of

2. where value is the element, we are searching for in array “arr.”

Output

2. Returns the index of an array element, where arr[index]=value

Pseudo Code

2. For each index from index=1 to n (where n is the last index of arr)

3. If arr[index]=value, then set the answer to the index value

4. Return the value of the answer as output

Getting Started

The article demonstrates the use of linear search inside an integer array in a console application. Firstly, let’s write code for linear function as per pseudo code. Iterate over an integer array and returns array index where a[i]==x and -1 if not found.

Finally, let’s write code to utilize the linear function.

1. Prepare an integer array with the following elements. 1, 4, 5, 7, 9, 22

2. Display all elements on the console window.

3. Take user input from the console which element to search in an array.

4. Call LinearSearch function created with both array and element to search.

5. If index!=-1 then output “Element {value} found at index {index}.”

Case 1 Output

Current rray Elements 1 , 4 , 5 , 7 , 9 , 22
Enter the element to be searched
5
Element 5 found at index 2

Case 2 Output

Current rray Elements 1 , 4 , 5 , 7 , 9 , 22
Enter the element to be searched
100

Github Repo

Please find below the GitHub repository demonstrate linear search using the .Net 5 console application.

https://github.com/ssukhpinder/LinearSearch

Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.

See All