Advertisement
jbn6972

Untitled

Dec 8th, 2023
581
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Linear - straight line
  4. // Linear search - search in a straight line
  5.  
  6. // 1. just check if the elemnt is present
  7. // 2. tell u to return the index of the place where it was found ... return -1 if its not there
  8.  
  9. // arr = 1 2 3 4 5 5 7 8 9 10
  10.  
  11. // key = 6
  12.  
  13. // 1 - 6 x
  14. // 2 - 6 x
  15. // 3 - 6 x
  16. // 4 - 6 x
  17. // 5 - 6 x
  18. // 5 - 6 x
  19. // 6 - 6 match found
  20.  
  21. // 1. true 1. false
  22. // 2. 6    2. -1
  23.  
  24. int linear_search_type1(int arr[100], int n, int key)
  25. {
  26.     for (int i = 0; i < n; i++)
  27.     {
  28.         if (arr[i] == key)
  29.         {
  30.             return 1;
  31.         }
  32.     }
  33.  
  34.     return 0;
  35. }
  36.  
  37. int linear_search_type2(int arr[100], int n, int key)
  38. {
  39.     for (int i = 0; i < n; i++)
  40.     {
  41.         if (arr[i] == key)
  42.         {
  43.             return i;
  44.         }
  45.     }
  46.  
  47.     return -1;
  48. }
  49.  
  50. int main()
  51. {
  52.     int arr[100], n, key;
  53.     printf("Enter the number of elements :: ");
  54.     scanf("%d", &n);
  55.  
  56.     printf("\nEnter %d elements : \n", n);
  57.     for (int i = 0; i < n; i++)
  58.     {
  59.         scanf("%d", &arr[i]);
  60.     }
  61.     getchar();
  62.     printf("Enter the value of key to be searched :: ");
  63.     scanf("%d", &key);
  64.  
  65.     // type 1
  66.     // int res = linear_search_type1(arr, n, key);
  67.     // if (res)
  68.     // {
  69.     //     printf("\nKey is present in the array");
  70.     // }
  71.     // else
  72.     // {
  73.     //     printf("\nKey is not present in the array");
  74.     // }
  75.  
  76.     // type 2
  77.     int res = linear_search_type2(arr, n, key);
  78.     if (res != -1)
  79.     {
  80.         printf("\nKey is present in the array at index :: %d", res);
  81.     }
  82.     else
  83.     {
  84.         printf("\nKey is not present in the array");
  85.     }
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement