Searching Algorithms (Linear Search, Binary Search) Gaming Project in C++

Explanation

  1. Linear Search:
    • linearSearch(const vector<int>& arr, int target): This function iterates through each element in the array to find the target value.
      • Parameters:
        • arr: The array in which to search.
        • target: The value to search for.
      • Logic: It checks each element until it finds the target or reaches the end of the array.
      • Return: Returns the index of the target if found; otherwise, returns -1.
  2. Binary Search:
    • binarySearch(const vector<int>& arr, int target): This function performs a binary search on a sorted array to find the target value.
      • Parameters:
        • arr: The sorted array in which to search.
        • target: The value to search for.
      • Logic: It repeatedly divides the search interval in half, comparing the target value with the middle element until the target is found or the interval is empty.
      • Return: Returns the index of the target if found; otherwise, returns -1.
  3. Main Function:
    • Initializes a sorted array arr and prompts the user to enter a number to search for.
    • Calls both linearSearch() and binarySearch() functions with the entered number.
    • Displays the results of both searches.

Notes:

  • Linear Search is simple and works for unsorted arrays but is less efficient (O(n) time complexity).
  • Binary Search is efficient for sorted arrays with a time complexity of O(log n), but requires the array to be sorted.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top