Algorithm na Neman layi (Linear Search) a C++- Bayani, Misali, da Lamba

Algorithm bincike na linzamin kwamfuta hanya ce mai sauƙi da ake amfani da ita don nemo takamaiman abu a cikin jeri. Wannan algorithm yana aiki ta hanyar bibiyar kowane kashi a cikin jeri har sai an sami abin da ake so ko kuma an ketare gabaɗayan lissafin.

Yadda Ake Aiki

  1. Fara daga kashi na farko a lissafin.
  2. Kwatanta kashi na yanzu tare da ƙimar manufa.
  3. Idan kashi na yanzu yayi daidai da ƙimar manufa, algorithm ya ƙare kuma ya dawo da matsayin kashi.
  4. Idan ba haka ba, ci gaba da maimaitawa ta ragowar abubuwan da ke cikin lissafin.
  5. Idan jeri duka ya ketare ba tare da gano abin da ake nufi ba, algorithm ɗin yana dawo da ƙimar da ba a samu ba.

Misali

Bari mu ce muna da lissafin lamba kuma muna son nemo lamba 34 a cikin jerin.

Jerin: {12, 45, 67, 89, 34, 56, 23, 90}

  1. Fara a kashi na farko: 12. Ba lambar da ake so ba.
  2. Matsar zuwa kashi na gaba: 45. Ba lambar da ake so ba.
  3. Ci gaba da ragowar abubuwan: 67, 89, 34. Abu na 34 yayi daidai da lambar da ake so.
  4. Algorithm ya ƙare kuma ya dawo da matsayin 34, wanda shine 4.

Misali Code a C++

#include <iostream>  
#include <vector>  
  
int linearSearch(const std::vector<int>& arr, int target) {  
    for(int i = 0; i < arr.size(); ++i) {  
        if(arr[i] == target) {  
            return i;  
        }  
    }  
    return -1;  
}  
  
int main() {  
    std::vector<int> numbers = {12, 45, 67, 89, 34, 56, 23, 90};  
    int target = 34;  
  
    int result = linearSearch(numbers, target);  
  
    if(result != -1) {  
        std::cout << "Element " << target << " found at position " << result << std::endl;  
    } else {  
        std::cout << "Element " << target << " not found in the array" << std::endl;  
    }  
  
    return 0;  
}  

A cikin misalin da aka bayar, mun yi amfani da linearSearch aikin don nemo lamba 34 a cikin jerin lambobin. Sakamakon zai zama matsayi na 34 a cikin jerin(matsayi sun fara daga 0) ko -1 idan ba a samo lambar ba.