Linear search

Example:-

if arr={12,14,18,16,15}

search =15, then output will be “element found at index 4”.

Steps:-

  • Run a loop to iterate array element.
  • check every array element with search element. if both are equal then return index of array element
  • end of loop.
  • return -1(search element not found in the array).

Linear search in java:-

import java.util.*;
public class LinearSearch {
        public static int linear_search(int[]array,int search) {
            for(int i=0;i<array.length;i++) {
                if(array[i]==search) {
                    return i;
                }
            }return -1;
        }

        public static void main(String[] args) {
            Scanner sc = new Scanner (System.in);
            System.out.println("Enter the size of array");
            int n=sc.nextInt()	;
            int[]array=new int[n];
            for(int i=0;i<n;i++) {
                array[i]=sc.nextInt();
            }
            System.out.println("Enter the element for search");
            int search=sc.nextInt();
            int result=linear_search(array,search);
            if(result==-1) {
                System.out.println("Element not found");
            }
            else {
                System.out.println("Element found at index " + result);
            }
        }

    }

Output(Element not Found in Linear Search):-

Output(Element not Found in Linear Search)

Output (Element Found in Linear Search):-

Output (Element Found in Linear Search):-

Linear Search in C

include<stdio.h> #include<stdbool.h> int main() {
int array[] = {1,2,3,4,56,6};
int search = 60;
int i;
bool flag= false;
// linear search in C
for(i=0;i<6;i++)
{
if(array[i]==search)
{
flag=true;
printf(“search element is found at index %d”,i);
break;
}
}
if(!flag)
{
printf(“search element is not in array”);
}
return 0;
}

Similar Java Tutorials

Leave a Comment