Write a program to find the element in an array.
Use of Linear Search
Example 1:
Input: arr[]={1,4,3,5,6,2},target=3
Output: Element is found
Example 2:
Input: arr[]={1,4,3,5,6,2},target=7
Output: Element is not found
Approach
Java
public class LinearSearch {public static void main(String[] args) {int arr[] = { 1, 4, 3, 5, 6, 2 };int target = 3;if (searchElement(arr, target))System.out.println("Element is found");elseSystem.out.println("Element is not found");}private static boolean searchElement(int[] arr, int target) {for (int i : arr) {if (i == target)return true;}return false;}}// Time Complexity : O(n)// Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Function to find the element in arrayint linearSearch(int arr[],int n,int target){for(int i=0;i<n;i++){if(arr[i]==target)return i;}return -1;}int main(){int arr[]={1,4,3,5,6,2};int target=3;int n=sizeof(arr)/sizeof(arr[0]);int index=linearSearch(arr,n,target);if(index!=-1)cout<<"Element is found\n";elsecout<<"Element is not found\n";return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment