Problem

Find a pattern in a given string.

Search – Pattern in a String Using Brute Force Search

 

Use Case:- To find occurrences of a word in a given text.

Problem Analysis:-

    • Input: The method will take 2 parameters as input.
      • String Text
      • Pattern
    • Process:
      • Traversed through the text array’s elements using while loop to match pattern
        • With each iteration inside outer while loop: there is another while loop which matches each character in pattern with text and accordingly increase value of childIndex
        • If value of childIndex is equal to pattern>length, pattern is found inside text.
    • Output: Index Value if pattern is found else return -1

Solution:-

FindPatterInStringWithBFS Find a pattern in a given string c# Data Structures and Algorithms   Ohbly.com

Output:-FindPatterInStringWithBFS-o Find a pattern in a given string c# Data Structures and Algorithms   Ohbly.com

Analysis:-  Since there is a loop inside a loop the Time complexity is O(m*n)

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;
}
s
    int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    Console.WriteLine($"Searched Value found at index: { SearchSortedArray(arr, 7) } ");
}