03 Tem

C# Sequential Search Example

Sequential search(Linear search) is the simplest search algorithm. It is a special case of brute-force search. It is a method for finding a particular value in a list. To achieve this, it checks every one of its elements one.

Usage:

            //Sorted array
            int[] arr = new int[10]
            {
                1, 2, 4, 11, 20, 28, 48, 84, 96, 106
            };

            int index = SequentialSearch(arr, 20);
            Console.WriteLine("Index of 20 value in array is " + index.ToString());    
            
            //Output:
            //Index of 20 value in array is 4

Sequential Search Implementation:

        private int SequentialSearch(int[] arr, int searchNumber)
        {
            arr[arr.Length - 1] = searchNumber;
            
            int i;
            for (i = 0; arr[i] != searchNumber; i++);
            return (i < arr.Length -1) ? i : -1;
        }

See Also:
Binary Search