Advertisement
STANAANDREY

qsort and bsearch

Mar 2nd, 2023
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int comp(const void *p1, const void *p2) {
  5.   const float nr1 = *(const float*)p1;
  6.   const float nr2 = *(const float*)p2;
  7.   return nr1 - nr2;
  8. }
  9.  
  10. int main(void) {
  11.   unsigned n;
  12.   scanf("%u", &n);
  13.   float *arr = (float*)calloc(sizeof(float), n), x;
  14.   if (arr == NULL) {
  15.     perror("");
  16.     exit(EXIT_FAILURE);
  17.   }
  18.   for (unsigned i = 0; i < n; i++) {
  19.     scanf("%f", arr + i);
  20.   }
  21.  
  22.   qsort(arr, n, sizeof(float), comp);
  23.  
  24.   for (unsigned i = 0; i < n; i++) {
  25.     printf("%g ", arr[i]);
  26.   }
  27.   puts("");
  28.  
  29.   scanf("%f", &x);
  30.   float *p = bsearch(&x, arr, n, sizeof(float), comp);
  31.   if (p != NULL) {
  32.     printf("%g found at pos %ld\n", x, p - arr);
  33.   } else {
  34.     printf("%g not found!\n", x);
  35.   }
  36.  
  37.   free(arr);
  38.   return 0;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement