A linear search sequentially checks each element of the list until it finds an element that matches the target value.
If the algorithm reaches the end of the list, the search terminates unsuccessfully.
int search(int arr[], int N, int x)
{
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, N, x);
(result == -1)?
printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
class GFG {
public static int search(int arr[], int N, int x)
{
for (int i = 0; i < N; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
public static void main(String args[])
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int result = search(arr, arr.length, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present at index "
+ result);
}
}
def search(arr, N, x):
for i in range(0, N):
if (arr[i] == x):
return i
return -1
if __name__ == "__main__":
arr = [2, 3, 4, 10, 40]
x = 10
N = len(arr)
result = search(arr, N, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result)