linear search 1

linear search

#include 

using namespace std; 

int search(int arr[], int n, int key) 
{ 
    int i; 
    for (i = 0; i < n; i++) 
        if (arr[i] == key) 
            return i; 
    return -1; 
} 

int main() 
{ 
    int arr[] = { 99,4,3,8,1 }; 
    int key = 8; 
    int n = sizeof(arr) / sizeof(arr[0]); 

    int result = search(arr, n, key); 
    (result == -1) 
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result; 

    return 0; 
}

Here is what the above code is Doing:
1. We have an array arr[] of size n.
2. We are searching for a key in the array.
3. If the key is present in the array, then we return its index.
4. If the key is not present in the array, then we return -1.

Time Complexity: O(n)

Similar Posts