You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.c 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include "common.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct timespec get_time(void)
  5. {
  6. struct timespec start_time;
  7. clock_gettime(CLOCK_MONOTONIC, &start_time);
  8. return start_time;
  9. }
  10. struct timespec time_diff(struct timespec* ts1, struct timespec* ts2)
  11. {
  12. static struct timespec ts;
  13. ts.tv_sec = ts1->tv_sec - ts2->tv_sec;
  14. ts.tv_nsec = ts1->tv_nsec - ts2->tv_nsec;
  15. if (ts.tv_nsec < 0) {
  16. ts.tv_sec--;
  17. ts.tv_nsec += 1000000000;
  18. }
  19. return ts;
  20. }
  21. struct timespec get_duration(struct timespec* ts)
  22. {
  23. struct timespec time = get_time();
  24. return time_diff(&time, ts);
  25. }
  26. void print_time(struct timespec* ts)
  27. {
  28. long ns = ts->tv_nsec % 1000;
  29. long us = (ts->tv_nsec / 1000) % 1000;
  30. long ms = (ts->tv_nsec / 1000000) % 1000;
  31. long s = (ts->tv_nsec / 1000000000) % 1000 + ts->tv_sec;
  32. long t = (s * 1000000000) + (ms * 1000000) + (us * 1000) + ns;
  33. printf("%3lds %3ldms %3ldus %3ldns %12ld", s, ms, us, ns, t);
  34. }
  35. int* read_int_array(unsigned n)
  36. {
  37. int* array = (int*)malloc(n * sizeof(unsigned));
  38. for (unsigned i = 0; i < n; ++i) {
  39. scanf("%i", &array[i]);
  40. }
  41. return array;
  42. }
  43. void read_input(int** array, unsigned* n)
  44. {
  45. printf("Enter n: ");
  46. scanf("%u", n);
  47. printf("Enter %u integers: ", 2 * *n);
  48. *array = read_int_array(2 * *n);
  49. }
  50. void print_array(int* array, unsigned n)
  51. {
  52. for (unsigned i = 0; i < n; ++i) {
  53. printf("%i ", array[i]);
  54. }
  55. printf("\n");
  56. }
  57. void merge_sort_merge_seq(int* array, unsigned l, unsigned m, unsigned h)
  58. {
  59. unsigned i = l, j = m + 1, k = 0;
  60. int tmp[h - l + 1];
  61. while (i <= m && j <= h) {
  62. if (array[i] <= array[j]) {
  63. tmp[k++] = array[i++];
  64. }
  65. else {
  66. tmp[k++] = array[j++];
  67. }
  68. }
  69. while (i <= m) {
  70. tmp[k++] = array[i++];
  71. }
  72. while (j <= h) {
  73. tmp[k++] = array[j++];
  74. }
  75. for (--k; k != (unsigned)-1; --k) {
  76. array[l + k] = tmp[k];
  77. }
  78. }
  79. void merge_sort_sub_seq(int* array, unsigned l, unsigned h)
  80. {
  81. if (l < h) {
  82. unsigned m = (l + h) / 2;
  83. merge_sort_sub_seq(array, l, m);
  84. merge_sort_sub_seq(array, m + 1, h);
  85. merge_sort_merge_seq(array, l, m, h);
  86. }
  87. }
  88. void merge_sort_seq(int* array, unsigned s)
  89. {
  90. merge_sort_sub_seq(array, 0, s - 1);
  91. }