Sunday, December 17, 2023

Linear Search

 // Linear Search

#include <iostream>  

using namespace std;  

int linearSearch(int a[], int n, int val) {  

  for (int i = 0; i < n; i++)  

    {  

        if (a[i] == val)  

        return i+1;  

    }  

  return -1;  

}  

int main() {  

  int a[] = {69, 39, 29, 10, 56, 40, 24, 13, 51};

  int val = 56; // value to be searched  

  int n = sizeof(a) / sizeof(a[0]); // size of array  

  int result = linearSearch(a, n, val);

  cout<<"The elements of the array are - ";  

  for (int i = 0; i < n; i++)  

  cout<<a[i]<<" ";    

  cout<<"\nElement to be searched is - "<<val;    

  if (result == -1)  

  cout<<"\nElement is not present in the array";  

  else  

  cout<<"\nElement is present at "<<result<<" position of array";  

  return 0;  

}

No comments:

Post a Comment

A physicist confesses that the electron is round and that Jesus rose from the dead. (Bengali)

একজন পদার্থবিজ্ঞানী স্বীকার করেন যে ইলেকট্রন গোলাকার এবং যিশু মৃতদের মধ্য থেকে পুনরুত্থিত হয়েছিলেন। আমার নিজের বিশ্বাস প্রমাণ দ্বারা প্রভাব...