Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- // Linear - straight line
- // Linear search - search in a straight line
- // 1. just check if the elemnt is present
- // 2. tell u to return the index of the place where it was found ... return -1 if its not there
- // arr = 1 2 3 4 5 5 7 8 9 10
- // key = 6
- // 1 - 6 x
- // 2 - 6 x
- // 3 - 6 x
- // 4 - 6 x
- // 5 - 6 x
- // 5 - 6 x
- // 6 - 6 match found
- // 1. true 1. false
- // 2. 6 2. -1
- int linear_search_type1(int arr[100], int n, int key)
- {
- for (int i = 0; i < n; i++)
- {
- if (arr[i] == key)
- {
- return 1;
- }
- }
- return 0;
- }
- int linear_search_type2(int arr[100], int n, int key)
- {
- for (int i = 0; i < n; i++)
- {
- if (arr[i] == key)
- {
- return i;
- }
- }
- return -1;
- }
- int main()
- {
- int arr[100], n, key;
- printf("Enter the number of elements :: ");
- scanf("%d", &n);
- printf("\nEnter %d elements : \n", n);
- for (int i = 0; i < n; i++)
- {
- scanf("%d", &arr[i]);
- }
- getchar();
- printf("Enter the value of key to be searched :: ");
- scanf("%d", &key);
- // type 1
- // int res = linear_search_type1(arr, n, key);
- // if (res)
- // {
- // printf("\nKey is present in the array");
- // }
- // else
- // {
- // printf("\nKey is not present in the array");
- // }
- // type 2
- int res = linear_search_type2(arr, n, key);
- if (res != -1)
- {
- printf("\nKey is present in the array at index :: %d", res);
- }
- else
- {
- printf("\nKey is not present in the array");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement