Linear Search Algorithm With C++

In this lecture we showed an example of C++ function that performs a linear search on an array, also we showed how to perform Linear Search Algorithm without function:

Linear Search With Function

int linear_search(int arr[], int n, int x) {
  for (int i = 0; i < n; i++) {
    if (arr[i] == x) {
      return i;
    }
  }
  return -1;
}

This function takes an array arr, its size n, and the element x that you want to search for as arguments. It returns the index of x in the array if it is found, or -1 if it is not found.

The function works by iterating through the elements of the array, one by one, until it finds the element that you are searching for. This makes the linear search algorithm relatively simple to implement, but it can be slow for large arrays, as it has a time complexity of O(n) in the worst case.

In contrast, the binary search algorithm is much faster for large arrays, as it has a time complexity of O(log n) in the worst case. However, it requires that the array is sorted in ascending order, which may not always be possible or desirable.

Linear Search Without Function

#include<iostream>
using namespace std;

int main()
{
    int Array[10]={10,20,25,35,43,50,60,80,90,95};
    int i;
    int item = 35;

    for(i=0; i<10; i++)
    {
        if(Array[i]==item)
        {
            cout<<"Item found at position:"<<i;
        }
    }
    return 0;
}

Leave a Comment