int linearSearch(int a[], int first, int last, int key) { // function: // Searches a[first]..a[last] for key. // returns: index of the matching element if it finds key, // otherwise -1. // parameters: // a in array of (possibly unsorted) values. // first, last in lower and upper subscript bounds // key in value to search for. // returns: // index of key, or -1 if key is not in the array. for (int i=first; i<=last; i++) { if (key == a[i]) { return i; } } return -1; // failed to find key }
Chat with our AI personalities
O(N) where N is the number of elements in the array you are searching.So it has linear complexity.
To search a particular element from the vector, use the find() algorithm. If the vector is sorted, you can use the binary_search() algorithm to improve efficiency. Both algorithms can be found in the <algorithm> header in the C++ standard library.
What you're describing is called a sequential search or linear search.
The best search programs to attempt writing in C are the following: Linear search (simplest), Binary search (faster) Hash search (fastest).
Binary Search Algorithm