Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. /* ЗАДАЧА №3
  2. *
  3. * Найти в массиве целых чисел три минимальных числа. Числа могут повторяться.
  4. * Для массива [2, 1, 0, 1] ответ будет [0, 1, 1].
  5. *
  6. * ПИНФ-11, Нефедов Д. В. — <eanmos@ya.ru>.
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10.  
  11. #define ARRLEN(a) (sizeof(a) / sizeof(a[0]))
  12. #define SWAPINT(a, b) do { const int tmp = (*a); (*a) = (*b); (*b) = tmp; } while (0)
  13.  
  14. static void sortThreeElementsArray(int a[3])
  15. {
  16. if (a[0] > a[2])
  17. SWAPINT(&a[0], &a[2]);
  18.  
  19. if (a[1] > a[2])
  20. SWAPINT(&a[1], &a[2]);
  21.  
  22. if (a[0] > a[1])
  23. SWAPINT(&a[0], &a[1]);
  24. }
  25.  
  26. static int *getThreeLowestValues(const int a[], size_t n)
  27. {
  28. static int ret[3];
  29.  
  30. for (size_t i = 0; i < 3; i++)
  31. ret[i] = INT_MAX;
  32.  
  33. for (size_t i = 0; i < n; i++) {
  34. if (a[i] < ret[2]) {
  35. ret[2] = a[i];
  36. sortThreeElementsArray(ret);
  37. }
  38. }
  39.  
  40. return ret;
  41. }
  42.  
  43. int main(void)
  44. {
  45. const int array[] = {-4, 20, 1, 0, 9, 4, 12, 4, 7, 3};
  46.  
  47. const int *answer = getThreeLowestValues(array, ARRLEN(array));
  48.  
  49. for (size_t i = 0; i < 3; i++)
  50. printf("%d ", answer[i]);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement