Linear Search .Net

ssukhpinder

Sukhpinder Singh

Posted on May 25, 2021

Linear Search .Net

Searches particular value within a data structure.

Background

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)”

  • where arr is the array to search inside of
  • where value is the element, we are searching for in array “arr.”

Output

  • Returns -1, if element not found
  • Returns the index of an array element, where arr[index]=value

Pseudo Code

  • Set answer to -1
  • For each index from index=1 to n (where n is the last index of arr)
  • If arr[index]=value, then set the answer to the index value
  • 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 LinearSearchfunction created with both array and element to search.
  5. If index!=-1 then output “Element {value} found at index {index}.”
  6. Else then output “Element not found.”

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
Enter fullscreen mode Exit fullscreen mode

Case 2 Output

    Current rray Elements 1 , 4 , 5 , 7 , 9 , 22
    Enter the element to be searched
    100
    Element not found
Enter fullscreen mode Exit fullscreen mode

Github Repo

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


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

Follow me on C# Publication,

LinkedIn,Instagram,Twitter,Dev.to,Pinterest,Substack,Wix.

💖 💪 🙅 🚩
ssukhpinder
Sukhpinder Singh

Posted on May 25, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related