1
1
// C++ program to perform TimSort.
2
2
#include < algorithm>
3
+ #include < cassert>
3
4
#include < iostream>
5
+ #include < numeric>
4
6
5
7
const int RUN = 32 ;
6
8
7
9
// this function sorts array from left index to to right index which is of size
8
10
// atmost RUN
9
11
void insertionSort (int arr[], int left, int right) {
10
12
for (int i = left + 1 ; i <= right; i++) {
11
- int temp = arr[i];
13
+ const int temp = arr[i];
12
14
int j = i - 1 ;
13
15
while (arr[j] > temp && j >= left) {
14
16
arr[j + 1 ] = arr[j];
@@ -21,7 +23,7 @@ void insertionSort(int arr[], int left, int right) {
21
23
// merge function merges the sorted runs
22
24
void merge (int arr[], int l, int m, int r) {
23
25
// original array is broken in two parts, left and right array
24
- int len1 = m - l + 1 , len2 = r - m;
26
+ const int len1 = m - l + 1 , len2 = r - m;
25
27
int *left = new int [len1], *right = new int [len2];
26
28
for (int i = 0 ; i < len1; i++) left[i] = arr[l + i];
27
29
for (int i = 0 ; i < len2; i++) right[i] = arr[m + 1 + i];
@@ -74,8 +76,8 @@ void timSort(int arr[], int n) {
74
76
for (int left = 0 ; left < n; left += 2 * size) {
75
77
// find ending point of left sub array
76
78
// mid+1 is starting point of right sub array
77
- int mid = left + size - 1 ;
78
- int right = std::min ((left + 2 * size - 1 ), (n - 1 ));
79
+ const int mid = std::min (( left + size - 1 ), (n - 1 )) ;
80
+ const int right = std::min ((left + 2 * size - 1 ), (n - 1 ));
79
81
80
82
// merge sub array arr[left.....mid] & arr[mid+1....right]
81
83
merge (arr, left, mid, right);
@@ -89,10 +91,29 @@ void printArray(int arr[], int n) {
89
91
std::cout << std::endl;
90
92
}
91
93
94
+ /* *
95
+ * @brief self-test implementation
96
+ * @returns void
97
+ */
98
+ void tests () {
99
+ // Case: array of length 65
100
+ constexpr int N = 65 ;
101
+ int arr[N];
102
+
103
+ std::iota (arr, arr + N, 0 );
104
+ std::reverse (arr, arr + N);
105
+ assert (!std::is_sorted (arr, arr + N));
106
+
107
+ timSort (arr, N);
108
+ assert (std::is_sorted (arr, arr + N));
109
+ }
110
+
92
111
// Driver program to test above function
93
112
int main () {
113
+ tests (); // run self test implementations
114
+
94
115
int arr[] = {5 , 21 , 7 , 23 , 19 };
95
- int n = sizeof (arr) / sizeof (arr[0 ]);
116
+ const int n = sizeof (arr) / sizeof (arr[0 ]);
96
117
printf (" Given Array is\n " );
97
118
printArray (arr, n);
98
119
0 commit comments