mario::konrad
programming / C++ / sailing / nerd stuff
Algorithm: Linear Search
© 2005 / Mario Konrad

Description

TODO:DESCRIPTION

C++

search_linear.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <algorithm>
#include <vector>

template <typename T, class ForwardIterator>
ForwardIterator search_linear(
    ForwardIterator begin,
    ForwardIterator end,
    T const & element)
{
    while (begin != end) {
        if (*begin == element)
            return begin;
        ++begin;
    }
    return end;
}

int main(int, char **)
{
    std::vector<int> v{ 60, 50, 10, 80, 0, 40, 90, 20, 70, 30, 10 };
    std::sort(v.begin(), v.end());

    auto i = search_linear(v.begin(), v.end(), 60);
    if (i == v.end())
        std::cout << "element not found" << std::endl;
    else
        std::cout << "element found " << *i << " at index "
            << i - v.begin() << std::endl;
    return 0;
}

Scheme

search_linear.scm:

1
2
3
4
5
6
7
8
9
10
11
(define (search_linear vec element)
    (cond
        ((null? vec) #f)
        ((not (list? vec)) #f)
        ((= (car vec) element) element)
        (else (search_linear (cdr vec) element))))

(display (search_linear '(60 50 10 80 0 40 90 20 70 30 10) 80))
(newline)

(exit)