Linear Search Algorithm with C++ Code | Data Structures & Algorithms

In computer science, a linear search algorithm or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.

Linear Search Diagram –

linear search algorithm

As you can see in the diagram above, we have an integer array data structure with some values. We want to search for the value (98) which is at 5th position in this array. Since we are performing the linear search algorithm we start from the beginning of the array and check for matching values till we find a match.

Algorithm to perform Linear Search –
  1. Take the input array arr[] from user.
  2. Take element(x) you want to search in this array from user.
  3. Set flag variable as -1
  4. LOOP : arr[start] -> arr[end]
    1. if match found i.e arr[current_postion] == x then
      • Print “Match Found at position” current_position.
      • flag = 0
      • abort
  5. After loop check flag variable.
    1. if flag == -1
      • print “No Match Found”
  6. STOP
C++ Program to Implement Linear Search
#include < iostream >
  using namespace std;

void linearSearch(int a[], int n) {
  int temp = -1;

  for (int i = 0; i < 5; i++) {
    if (a[i] == n) {
      cout << "Element found at position: " << i + 1 << endl;
      temp = 0;
      break;
    }
  }

  if (temp == -1) {
    cout << "No Element Found" << endl;
  }

}

int main() {
  int arr[5];
  cout << "Please enter 5 elements of the Array" << endl;
  for (int i = 0; i < 5; i++) {
    cin >> arr[i];
  }
  cout << "Please enter an element to search" << endl;
  int num;
  cin >> num;

  linearSearch(arr, num);

  return 0;
}
YouTube video tutorials –

Leave a Reply

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