Skip to content

Commit 1e363ee

Browse files
committed
fix: fix bug in timSort
1 parent 2dadbf7 commit 1e363ee

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

sorting/tim_sort.cpp

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// C++ program to perform TimSort.
22
#include <algorithm>
3+
#include <cassert>
34
#include <iostream>
5+
#include <numeric>
46

57
const int RUN = 32;
68

@@ -74,7 +76,7 @@ void timSort(int arr[], int n) {
7476
for (int left = 0; left < n; left += 2 * size) {
7577
// find ending point of left sub array
7678
// mid+1 is starting point of right sub array
77-
int mid = left + size - 1;
79+
int mid = std::min((left + size - 1), (n - 1));
7880
int right = std::min((left + 2 * size - 1), (n - 1));
7981

8082
// merge sub array arr[left.....mid] & arr[mid+1....right]
@@ -89,8 +91,23 @@ void printArray(int arr[], int n) {
8991
std::cout << std::endl;
9092
}
9193

94+
void test(int n) {
95+
int *arr = new int[n];
96+
97+
std::iota(arr, arr + n, 0);
98+
std::reverse(arr, arr + n);
99+
assert(!std::is_sorted(arr, arr + n));
100+
101+
timSort(arr, n);
102+
assert(std::is_sorted(arr, arr + n));
103+
104+
delete[] arr;
105+
}
106+
92107
// Driver program to test above function
93108
int main() {
109+
test(65);
110+
94111
int arr[] = {5, 21, 7, 23, 19};
95112
int n = sizeof(arr) / sizeof(arr[0]);
96113
printf("Given Array is\n");

0 commit comments

Comments
 (0)