code:
/* Count Frequency in an Array(Optimized Version) Syed Ahmed Zaki -- 2017 */ #include<stdio.h> int linear_search(int A[],int n,int x) { int i; for(i=0; i<n; i++) if(A[i]==x) return i; return -1; } int main() { int x; int A[]= {5,6,7,8,9}; printf("Put value to search from an array:\n"); scanf("%d",&x); int out=linear_search(A,5,x); if(out==-1) { printf("%d is not found\n",x); } else { printf("%d is in index %d\n",x,out); } return 0; }
Another Code By Me:
/* Count Frequency in an Array(Optimized Version) Syed Ahmed Zaki -- 2017 */ #include<stdio.h> int linear_search(int *A,int n,int x) //*A is passing the value of the array address index { int i; for(i=0; i<n; i++) if(A[i]==x) return i; return -1; } int main() { int x,i,n; printf("Array Size:"); scanf("%d",&n); int A[10005]; printf("Please enter an array elements:"); for(i=0;i<n;i++) { scanf("%d",&A[i]); } printf("Put value to search from an array:\n"); scanf("%d",&x); int out=linear_search(A,5,x); if(out==-1) { printf("%d is not found\n",x); } else { printf("%d is in index %d\n",x,out); } return 0; }
Complexity:
Best Case: O(1)
Worst Case: O(n)
Average Case: O(n/2)=O(n)
Source: http://quiz.geeksforgeeks.org/linear-search/
Pseudocode Looks Like this:
SEARCH(A, v): for i = 1 to A.length if A[i] == v return i return NIL
source: http://clrs.skanev.com/02/01/03.html
Another Good Pseudocode:
LinearSearch(A,n,item) Begin for i=0 to n-1 by 1 do if A[i]==item then return i; end if end for return -1 End
Source: