Advertisement
vencinachev

LinearSearch

Mar 23rd, 2022
960
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <time.h>
  6. #include <math.h>
  7. #define COUNT 10
  8.  
  9. int *lsearch(void* key, void* arr, size_t n, size_t size, int (*cmp)(const void*, const void*)){
  10.     for (int i = 0; i < n * size; i += size){
  11.         if (cmp(key, arr + i) == 0){
  12.             return arr + i;
  13.         }
  14.     }
  15.     return NULL;
  16. }
  17.  
  18. //   *(int*)a
  19. int compare(const void* a, const void* b){
  20.     return *(int*)a - *(int*)b;
  21. }
  22.  
  23. int compareD(const void* a, const void* b){
  24.     if (fabs(a - b) < 0.001){
  25.         return 0;
  26.     } else if (a > b){
  27.         return 1;
  28.     }
  29.     return -1;
  30. }
  31.  
  32. struct rect {
  33.     double w;
  34.     double h;
  35. };
  36.  
  37. // area
  38. int compareRects(const void* a, const void* b){
  39.     struct rect r1 = *(struct rect*)a;
  40.     struct rect r2 = *(struct rect*)b;
  41.     double area1 = r1.w * r1.h;
  42.     double area2 = r2.w * r2.h;
  43.     if (fabs(area1 - area2) < 0.001){
  44.         return 0;
  45.     } else if (area1 > area2){
  46.         return 1;
  47.     }
  48.     return -1;
  49. }
  50.  
  51. int main(){
  52.     struct rect rectangles[10];
  53.  
  54.     srand(time(NULL));
  55.     int nums[COUNT];
  56.     for (int i = 0; i < COUNT; i++){
  57.         nums[i] = rand() % 100;
  58.     }
  59.     //qsort(nums, COUNT, sizeof(int), compare);
  60.     for (int i = 0; i < COUNT; i++){
  61.         printf("%d ", nums[i]);
  62.     }
  63.     putchar('\n');
  64.     int key = 20;
  65.     int* ptr = lsearch(&key, nums, COUNT, sizeof(int), compare);
  66.     if (ptr == NULL){
  67.         printf("%d is not found!\n", key);
  68.     } else {
  69.         printf("Element %d is found!\n", key);
  70.     }
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement