|
1 | 1 | /** |
2 | 2 | * @file |
3 | | - * @author [LJFP](https://github.com/ljfp/) |
4 | 3 | * @brief [Timsort](https://en.wikipedia.org/wiki/Timsort) implementation |
5 | 4 | * @details |
6 | 5 | * Timsort is a hybrid stable sorting algorithm, derived from merge sort and |
7 | 6 | * insertion sort, designed to perform well on many kinds of real-world data. |
8 | 7 | * Worst-case time complexity is O(n log n). |
9 | 8 | * Worst-case space complexity is O(n). |
| 9 | + * @author [LJFP](https://github.com/ljfp/) |
| 10 | + * @see merge_sort.c, insertion_sort.c |
10 | 11 | */ |
11 | 12 | #include <assert.h> |
12 | 13 | #include <stdio.h> |
13 | 14 | #include <stdlib.h> |
14 | 15 | #include <time.h> |
15 | 16 |
|
16 | 17 | #define min(a, b) \ |
17 | | - ((a) < (b) ? (a) : (b)) /* Macro to find the minimum of two numbers */ |
| 18 | + ((a) < (b) ? (a) : (b)) |
18 | 19 |
|
19 | 20 | /** |
20 | 21 | * @brief Performs insertion sort on a subarray |
21 | 22 | * @param arr Array to be sorted |
22 | 23 | * @param left Starting index of the subarray |
23 | 24 | * @param right Ending index of the subarray |
24 | 25 | */ |
25 | | -void insertionSort(int arr[], int left, int right) |
| 26 | +void insertion_sort(int arr[], int left, int right) |
26 | 27 | { |
27 | 28 | for (int i = left + 1; i <= right; i++) |
28 | 29 | { |
@@ -97,7 +98,7 @@ void timsort(int arr[], int n, int run_size) |
97 | 98 | /* Sort individual subarrays of size run_size */ |
98 | 99 | for (int i = 0; i < n; i += run_size) |
99 | 100 | { |
100 | | - insertionSort(arr, i, min((i + run_size - 1), (n - 1))); |
| 101 | + insertion_sort(arr, i, min((i + run_size - 1), (n - 1))); |
101 | 102 | } |
102 | 103 |
|
103 | 104 | /* Start merging from size run_size */ |
@@ -133,7 +134,7 @@ void test() |
133 | 134 | arr[i] = (rand() % 1000) - 500; /* Signed random numbers */ |
134 | 135 | } |
135 | 136 |
|
136 | | - /* Test with different run sizes */ |
| 137 | + /* Test with different run sizes but always a power of 2 */ |
137 | 138 | for (int run_size = 16; run_size <= 64; run_size *= 2) |
138 | 139 | { |
139 | 140 | /* Copy the original array to preserve it for each run size */ |
|
0 commit comments