Linear Search
- It is also Called as "Sequential Search".
- This is simplest method.
- It can be applied to sequential storage structure like files, array, or linked list.
- Advantages of Linear Search
- It is very simple method.
- It does not require the data to be sorted.
- It does not require any additional data structure.
- Disadvanatges of Linear Search
- If 'n' is very large, this method is very in efficient and slow.
- It's worst case complexity O(n).
- Analysis of sequential search
-The best case time complesxity Ω(1).
Worst Case:-The case occurs when the key is not found in array.
-The worst case time complexity O(n).
Average Case:-Average comparisons = n(n+1)/2n = (n+1)/2.
-The average case time complexity of this method is O(n).
CODE
👇
- #include <stdio.h>
- int linear_search(int a[10], int n, int key);
- int main()
- {
- int a[10], key, n, pos;
- printf("INPUT NUMBER OF ELEMENT IN ARRAY:");
- scanf("%d", &n);
- printf("ENTER %d NUMBERS:\n", n);
- for(int i=0; i<n; i++)
- scanf("%d", &a[i]);
- printf("ENTER NUMBER TO SEARCH:\n");
- scanf("%d", &key);
- pos=linear_search(a, n, key);
- if(pos == -1)
- printf("%d IS NOT PRESENT IN ARRAY!!\n", key);
- else
- printf("%d IS PRESENT IN ARRAY\n", key);
- return 0;
- }
- int linear_search(int a[10], int n, int key)
- {
- int i;
- for(i=0; i<n; i++)
- {
- if(a[i]==key)
- return 1;
- }
- return -1;
- }
👉Execute👈
//Output
/*
1]
INPUT NUMBER OF ELEMENT IN ARRAY:5
ENTER 5 NUMBERS:
1
3
5
7
9
ENTER NUMBER TO SEARCH:
5
5 IS PRESENT IN ARRAY
2]
INPUT NUMBER OF ELEMENT IN ARRAY:5
ENTER 5 NUMBERS:
1
3
5
7
9
ENTER NUMBER TO SEARCH:
6
6 IS NOT PRESENT IN ARRAY!!
*/
//ThE ProFessoR
Comments
Post a Comment