Basic programming - Linear Search
Question:
Given an array arr[] of n elements, write a function to search a given element x in arr[].
Example:
Input: arr[] = {10, 20, 80, 30, 60, 50, 100, 110, 130, 170}
x = 110;
Output: 6
Explanation: Element x is presented at index 6
Input: arr[] = {10, 20, 80, 30, 60, 50, 100, 110, 130, 170}
x = 175;
Output: -1
Explanation: Element x is not presented in arr[].
Source code:
Version 1
Idea
It is a very simple approach to find the target.
Go through each element which is equal to the target (Start from the index 0 of array). If the target doesn't exist in arry, return -1.
However, it is rarely used practically because other search algorithms are more efficient.
Time complexity: O(n)
1 |
|