LINEAR SEARCH – SHOUT CODERS

In computer science, a linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.
.
ALGORITHM:
Step 1: Initialize Array A and Variable X for searching element.
Step 2: Set i to 1 and initialize n as array size
Step 3: if i > n then go to step 8
Step 4: if A[i] = x then go to step 7
Step 5: Set i to i + 1
Step 6: Go to Step 3
Step 7: Print Element x Found at index i and go to step 9
Step 8: Print element not found
Step 9: Exit
.
C PROGRAM:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<stdio.h> // #include<conio.h> for windows only. int main() { int a[20],i,x,n; printf("\nEnter number of elements in array: "); scanf("%d",&n); printf("Enter %d integer(s)\n",n); for(i=0;i<n;++i) { printf("Enter Value: "); scanf("%d",&a[i]); } printf("\nEnter a number to search:"); scanf("%d",&x); for(i=0;i<n;++i) if(a[i]==x) break; if(i<n) printf("%d is present at location %d.\n",x,i+1); else printf("Element not found.\n"); return 0; } |
.
JAVA PROGRAM:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; class linear1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a[]=new int[20]; int i,x; System.out.print("\nEnter number of elements in array: "); int n=sc.nextInt(); System.out.println("Enter"+ n +" integer(s)"); for(i=0;i<n;i++) { a[i]=0; System.out.print("Enter Value: "); a[i]=sc.nextInt(); } System.out.print("\nEnter a number to search: "); x=sc.nextInt(); for(i=0;i<n;i++) if(a[i]==x) break; if(i<n) System.out.print(x+" is present at location "+(i+1)+"\n"); else System.out.print("Element not found.\n"); } } |
PYTHON PROGRAM:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
n=int(input("Enter number of elements in array: ")) print("Enter", n, "integer(s)") a=[] for i in range(n): v=int(input("Enter Value: ")) a.append(v) print(a) x=int(input("Enter a number to search: ")) flag=-1 for i in range(n): if(a[i]==x): flag=i break if(flag!=-1): print(x, " is present at location ", flag) else: print("Element not found.") |
.
Input / Output:
Enter number of elements in array: 5
Enter 5 integer(s)
Enter Value: 22
Enter Value: 23
Enter Value: 43
Enter Value: 56
Enter Value: 76
Enter a number to search:23
23 is present at location 2.
.
DESCRIPTION:
The time complexity of the above algorithm is: O(n). It is not widely used because for a value the whole array must be search that takes times for very large array size. There are Binary search we used instead of linear search. This programming steps is east to remember and a very good beginning for beginners.