Problem

Write a method to search the value among all the elements inside the sorted Array.

 Search – Binary Search

 

Use Case:- To use Binary Search as we know that 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 while loop
        • Inside while loop: Match searchValue with the array elements divided into half using the middle value.
    • Output: Index Value if searchValue is found else return -1

Solution:-

SearchSortedArray Write a method to search the value among all the elements inside the Sorted Array c# Data Structures and Algorithms   Ohbly.com
The whole code is shared below.

Output:-SearchSequenceBased-0 Write a method to search the value among all the elements inside the Sorted Array c# Data Structures and Algorithms   Ohbly.com

Analysis:-  Since half of the elements are traversed the Time complexity is O(logn)

Code:-

public static int SearchSortedArray(int[] intArray, int searchValue)
{
    int start = 0;
    int end = intArray.Length - 1;
    int middle;
    
    while (start <= end)
    {
        middle = start +  (end - start) /2 ;

        if ( searchValue == intArray[middle])
        {
            return middle;
        }
        else
        {
            if ( intArray[middle] < searchValue )
            {
                start = middle + 1;
            }
            else
            {
                end = middle - 1;
            }
        }
    }
    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: { SearchSortedArray(arr, 7) } ");
}