Linear Search Approach

The basic idea to find a number in an array involves going through each element of the array one by one, and comparing them with the target value until a match is found.

Steps to solve the problem:

  • Start from the element, in the array.
  • Compare the element with the target value.
  • If they match, provide the index of that element.
  • If not, move on to the element in the array.
  • Repeat steps 2-4 until either you reach the end of the array or find a match.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int binarySearch(int arr[], int left, int right, int target)
{
    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        }

        if (arr[mid] < target) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return -1;
}

// Drivers code
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int index = binarySearch(arr, 0, n - 1, target);

    if (index != -1) {
        cout << "Target found at index " << index << endl;
    }
    else {
        cout << "Target not found in the array." << endl;
    }

    return 0;
}
Java
import java.util.Arrays;

public class LinearSearch {
    // Implementing linear search method
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            // Check if the current element in the array matches the target
            if (arr[i] == target) {
                // If found, return the index where the target is located
                return i;
            }
        }
        // If the loop completes without finding the target, return -1 to indicate it's not in the array
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int target = 30;

        // Call the linearSearch method to search for the target in the array
        int index = linearSearch(arr, target);

        if (index != -1) {
            // If the index is not -1, the target was found; print the index
            System.out.println("Number found at index " + index);
        } else {
            // If the index is -1, the target was not found; print a message indicating so
            System.out.println("Number not found in the array.");
        }
    }
}
Python
# Implementing optimized linear search method
def linear_search_optimized(arr, target):
    for i, num in enumerate(arr):
        if num == target:
            return i
    return -1


# Driver code
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    target = 30

    index = linear_search_optimized(arr, target)

    if index != -1:
        print("Number found at index {}".format(index))
    else:
        print("Number not found in the array.")
C#
using System;

class LinearSearch
{
    // Implementing linear search method
    static int LinearSearchFunc(int[] arr, int target)
    {
        // Iterate through the array to find the target element
        for (int i = 0; i < arr.Length; i++)
        {
            // If the current element matches the target, return its index
            if (arr[i] == target)
            {
                return i;
            }
        }
        // Return -1 if the target element is not found in the array
        return -1;
    }

    // Driver code
    static void Main()
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        int target = 30;

        // Perform a linear search to find the target in the array
        int index = LinearSearchFunc(arr, target);

        // Output the result based on whether the target was found or not
        if (index != -1)
        {
            Console.WriteLine("Number found at index " + index);
        }
        else
        {
            Console.WriteLine("Number not found in the array.");
        }
    }
}
Javascript
// Implementing linear search method
function linearSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        // Check if the current element in the array matches the target
        if (arr[i] === target) {
            // If found, return the index where the target is located
            return i;
        }
    }
    // If the loop completes without finding the target, return -1 to indicate it's not in the array
    return -1;
}

// Main function
function main() {
    const arr = [10, 20, 30, 40, 50];
    const target = 30;

    // Call the linearSearch method to search for the target in the array
    const index = linearSearch(arr, target);

    if (index !== -1) {
        // If the index is not -1, the target was found; print the index
        console.log("Number found at index " + index);
    } else {
        // If the index is -1, the target was not found; print a message indicating so
        console.log("Number not found in the array.");
    }
}

// Invoke the main function
main();

Output
Target found at index 2





Time Complexity: O(n) The time complexity of linear search is O(n) because in worst case scenarios you may need to check every element in the array.
Auxiliary space: O(1) The space requirement is O(1) as you only require a handful of variables to keep track of the loop.

Find the Target number in an Array

Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities.

Examples:

Input: Array: {10, 20, 30, 40, 50} , Target: 30
Output: “Target found at index 2”

Input: Array: {10, 20, 30, 40, 50}, Target: 40
Output: “Target found at index 3”

Similar Reads

Linear Search Approach:

The basic idea to find a number in an array involves going through each element of the array one by one, and comparing them with the target value until a match is found....

Binary Search Approach:

When searching for a number in an array binary search is an algorithm that takes advantage of the sorted nature of the array. It does this by reducing the search space by half, in each iteration....

Hashing Approach:

Hashing is an approach that employs a hash function to map elements in an array to locations, within a data structure, usually known as a hash table. When you have an urgent need to locate a number this method proves to be highly effective....