Skip to content

Commit 5e70b30

Browse files
Fix: out-of-bounds issue in counting_sort_string.cpp (#3055)
1 parent b9c118f commit 5e70b30

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

sorting/counting_sort_string.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,21 @@
33

44
using namespace std;
55

6-
void countSort(string arr) {
7-
string output;
6+
void countSort(string& arr) {
7+
int n = arr.length();
8+
string output(n, ' '); // pre-allocate space
89

9-
int count[256], i;
10-
for (int i = 0; i < 256; i++) count[i] = 0;
10+
int count[256] = {0};
11+
for (int i = 0; i < n; ++i) ++count[(unsigned char)arr[i]];
1112

12-
for (i = 0; arr[i]; ++i) ++count[arr[i]];
13+
for (int i = 1; i < 256; ++i) count[i] += count[i - 1];
1314

14-
for (i = 1; i < 256; ++i) count[i] += count[i - 1];
15-
16-
for (i = 0; arr[i]; ++i) {
17-
output[count[arr[i]] - 1] = arr[i];
18-
--count[arr[i]];
15+
for (int i = 0; i < n; ++i) {
16+
output[count[(unsigned char)arr[i]] - 1] = arr[i];
17+
--count[(unsigned char)arr[i]];
1918
}
2019

21-
for (i = 0; arr[i]; ++i) arr[i] = output[i];
22-
20+
arr = output;
2321
cout << "Sorted character array is " << arr;
2422
}
2523

0 commit comments

Comments
 (0)