Problem
Write a method to search the value among all the elements inside the Array.
Search – Sequence-Based
Use Case:- Sequential Search as we have no idea whether the data in the array is sorted.
Problem Analysis:-
- Input: The method will take 2 parameters as input.
- Integer Array
- Value to be searched
- Process:
- Traversed through the array’s elements using for loop
- Inside for loop: Match searchValue with each element in the Array
- Traversed through the array’s elements using for loop
- Output: Index Value if searchValue is found else return -1
- Input: The method will take 2 parameters as input.
Solution:-
Output:-
Analysis:- Since all the elements are traversed sequentially the Time complexity is O(n)
Code:-
public static int SearchSequenceBased(int[] intArray, int searchValue) { for (int index = 0; index < intArray.Length; index++) { if (searchValue == intArray[index]) { return index; } } return -1; } public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Console.WriteLine($"Searched Value found at index: { SearchSequenceBased(arr, 7) } "); }