Linear Search:
Write a c program to generate random array of n integers and apply linear search to find value entered by user.
- Linear Search Algorithm:
Step 1: Start
Step 2: Accept n numbers in an array num and a number to be searched
Step 3: se ti=0 and flag=0
Step 4: if i<n then goto next step else goto step 7
Step 5: Compare num[i] and number
If equal then
set flag=1 and goto step 7
Step 6: i=i+1 and goto step 4
Step 7: if (flag=1) then
Print “Required number is found at location i+1”
else
Print “Require data not found”
Step 8: Stop
- Time Complexity:
Base Case: O(1)
Worst Case: O(n)
Average Case: O(n)
- Create a random array of n integers. Accept a value x from user and use linear search algorithm to check whether the number is present in the array or not and output the position if the number is present.
#include<stdio.h> #define max 10 int main() { int a[max],k,i,n,flag=0,index; printf("Enter n:"); scanf("%d",&n); generate(a,n); printf("Random elements are\n"); for(i=0;i<n;i++) printf("%d\n",a[i]); printf("Enter number to search: "); scanf("%d",&k); linearsearch(a,n,k); } void generate(int a[],int n) { int i; for(i=0;i<n;i++) a[i]=rand()%100; } void linearsearch(int a[],int n,int k) { int i,flag=0,index ; for(i=0;i<n;i++) if(a[i]==k) { flag=1; index=i; } if(flag==1) { printf("Element found at index %d",index+1); } else printf("Not Found"); }
Output :
Enter n:6 Random elements are 41 67 34 0 69 24 Enter number to search: 34 Element found at index 3 Process returned 0 (0x0) execution time : 6.261 s Press any key to continue.
0 Comments
Thanks,To visit this blog.